Tuesday, February 14, 2012

Sed reaources

Batch text replacement for multiple files with a shell script:

TMPFILE=./tmp.$$

for filename in *.txt; do
  sed 's/text_to_replace/something_to_replace_it_with/g' $filename > $TMPFILE
  mv $TMPFILE $filename # Comment this line out to not overwrite the original file.
fi

Replacing one string with another in multiple files using sed:

sed -i 's,text,replacement,g' *.txt
Recursively substituting text in many files with find and sed:

find . -type f -iname '*.txt' -exec sed -i 's,this,that,g' {} +

sed -f scriptname

If you have a large number of sed commands, you can put them into a file and use

sed -f sedscript <old >new
where sedscript could look like this:

# sed comment - This script changes lower case vowels to upper case
s/a/A/g
s/e/E/g
s/i/I/g
s/o/O/g
s/u/U/g
When there are several commands in one file, each command must be on a separate line.


A sed interpreter script

Another way of executing sed is to use an interpreter script. Create a file that contains:

#!/bin/sed -f
s/a/A/g
s/e/E/g
s/i/I/g
s/o/O/g
s/u/U/g

Click here to get file: CapVowel.sed
If this script was stored in a file with the name "CapVowel" and was executable, you could use it with the simple command:

CapVowel <old >new


No comments:

Post a Comment