SSS
SSS

Reputation: 2442

Using sed on multiple files in a script

I have a sed script to insert a line before a keyword "MYWORD" found in the file. My script is the following:

sed -e '/MYWORD/ i\MY NEW LINE TO BE INSERTED' <inputFilename >outputFilename

Since this will only occur on just one file how can I change my script to have this insert occur on every file in the directory?

Upvotes: 2

Views: 462

Answers (1)

ghoti
ghoti

Reputation: 46836

As nosid said, you can use the -i option to edit a file in place. Read the man page in YOUR operating system to determine exactly how to use -i. Then you can wrap sed in a little bit of shell script to identify and act on the file:

for this in foo*.txt; do
  sed -i'' -e 'your-sed-script' "$this"
done

That said, I'm not sure your insert method will work, or at least work reliably. I tested in FreeBSD and OS X, and it didn't work at all. My normal strategy for inserting lines is to use awk, instead. Thus (for example):

for this in foo*.txt; do
  awk '/MYWORD/{print "Extra line of text goes here."} 1' "$this" > "$this.$$"
  mv "$this.$$" "$this"
done

The awk line here searches for /MYWORD/ (an extended regular expression, whereas sed defaults to basic regular expressions). If it finds it, it first prints the "Extra" text. Then, the "1" evaluates as a "true" that will also print the current line. The effect is to insert the "Extra" text on the line before MYWORD.

Note that this isn't a good script. It's wasteful, piping and renaming files that haven't been modified. You could improve it by choosing to "mv" the temp file depending on an exit value from awk, or you could use cmp to determine if the file had changed, then clean up leftover tempfiles, etc... But it gets the point across.

Upvotes: 1

Related Questions