Substitute a Keyword In a File
October 9th, 2006 liewsheng Posted in Text Manipulation, perl, sed | Hits: 4829 |
Sometime I need to replace a keyword with another, I can’t just open a file and substitute 1 by 1. It is faster to using a single command line. There have more than 2 ways to do it, but I prefer this 2 command: perl and sed.
To substitute a word ‘abc’ to ‘def’ in a file xyz :
perl -pi -e 's/abc/def/;' xyz
or
sed -e 's/abc/def/' xyz > xyz_new
This 2 command will accept the RE(regular expression) as it input. for the perl command -p mean to loop inside the file, -i will replace in the file immediate match and -e specify the perl command to use.
Just like perl, -e provide to sed also represent the command to use. But the process text will print out to stdout not in the file, so we need to redirect it back to another file.
If you want to swap between 2 words, ‘abc def’ become ‘def abd’. Here want you need to enter:
perl -pi -e 's/(abc) (def)/$2$1/' xyz
or
sed -e 's/(abc) (def)/\2\1/' xyz > xyz_new
Live Chat!









April 4th, 2007 at 9:06 pm
You might want to add the g flag at the end in order to substitute _all_ occurrences in a line:
sed -e ’s/abc/def/g’ xyz > xyz_new
April 4th, 2007 at 9:48 pm
Great! g means global, search and replace it globally, instead of a line, it replace every single pattern it match. I usually like to do with -i. So it can be edit the file in place.
sed -e ’s/abc/def/g’ -i xyz