0

I have to write a batch file that search for a specific line in a file, and replace it with the filename.

To be specific, one file:

data
data
data
ABCD xyz <- this is the line that i have to replace. abcd always the same xyz always different
data
data

i'd like to change the xyz value to the name of the file without extension. So if the file is blabla.tpo then the file have look like:

data
data
ABCD blabla
data
....

I hope you guys can help me out. I'm not a programmer, these are 3d files and i have 1000 of them. I already googled every way, wrote hundreds of non working batch files. Tried FAR, notepad++ and who knows how much more without succes. If the program can do it, then i have to open files one by one, or it can't insert the filename, only exact string...

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • possible duplicate of [Find a string and replace specific letters in batch file](http://stackoverflow.com/questions/17085650/find-a-string-and-replace-specific-letters-in-batch-file) – Brian Tompsett - 汤莱恩 Dec 26 '14 at 09:59
  • It is a duplicate of [How can you find and replace text in a file using the Windows command-line environment?](http://stackoverflow.com/questions/60034/) Some tools in referenced topic can even run on multiple files. And of course there are also text editors which support a replace in all files of a directory tree. – Mofi Dec 26 '14 at 13:09

1 Answers1

0

Try Perl if you have it:

perl -ne 'if (/^(ABCD ).*$/) { print "$1blabla\n"; } else { print $_; }' inputfile.txt

The shell itself is not terribly great for that sort of task. You can probably do line-by-line reading (e.g. via read in Bash), but the replacement logic isn't that refined or powerful as that of Perl.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Thanks for your answer. Does this pearl can batch do this? I mean there is a folder with 100 file and every file have to base on this method. – Viczián Sándor Aug 23 '12 at 23:13
  • @VicziánSándor: Sure: `for i in *; do perl ... $i > $i.output; done` etc. The Windows shell has a similar construction. – Kerrek SB Aug 23 '12 at 23:16