Linux tips — III

It is common practice to substitute or change all occurrences of a certain word, date or number etc. with something else in a text file. In Linux, the most typical way of doing this, of course, is to use a text editor such as Vi (Vim) or Emacs, but there is a command line alternative, which is faster particularly for large files. This command, for example, will replace all occurrences of “word1” in “file1” with “word2”, and save the edited version as a new file, called “file2”:

sed “s/word1/word2/g” file1 > file2

sed is a Swiss knife. It can do a multitude of things as this nice tutorial explains. It is one of the most advanced command tool utilities in Linux. Its use is not limited to making simple substitutions, it is a complete stream editor.

There are alternatives to sed. If you are already familiar with the Perl programming language, you can make substitutions in a text file without having to use an editor, that is, from the command line:

perl -i -pe ‘s/word1/word2/;’ myFiles*

By adding a find statement in front of this command, you can edit all files in all sub-directories at once, something no text editor can provide. For example, this command will convert all “protected” Java methods to “private”, in all files ending with “.java”:

find . -name ‘*.java’ -print | xargs perl -pi -e’s/protected/private/’

Happy fast text substitutions!