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