Substitute a Keyword In a File

October 9th, 2006 liewsheng Posted in perl, sed, Text Manipulation | Hits: 40619 | 5 Comments »

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


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


sed -e 's/(abc) (def)/\2\1/' xyz > xyz_new

5 Responses to “Substitute a Keyword In a File”

  1. 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

  2. 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

  3. thanks for your post,great info.

  4. Thank you for your post. Loved it truly….

  5. I’m not that much of a online reader to be honest but your blogs really nice, keep
    it up! I’ll go ahead and bookmark your website to come back down the road.

    All the best

Leave a Reply