1 Comment

“sed”: Find and Replace Command on Linux Command Line

Sometimes we use IDE to find and replace strings in our file(s). IDEs have features to search for a keyword in all the files in a directory and replace with a given string. When you’re on Linux and using command line you can easily do this using the command “sed”.

According to the linux manual (man sed) “sed” is a stream editor which is used to perform basic text transformations on an input stream. With this command you can efficiently find and replace text in one or multiple files or you can keep the original file and make a new file with the replacement text.

To find and replace text in the original file the command is:

sed -i 's/find/replace/g' original.php

In the command above, “-i” option instructs to edit file(s) in place. “s” command attempts to match the pattern space against the supplied “find” string (which is a regular expression pattern). If the match is successful, then that portion of the pattern space which was matched is replaced with “replace” text. “g” is used to specify a global change, i.e. the string will be changed everywhere in the file(s) where it finds them. As mentioned earlier the “find” string is basically a regular expression pattern, and the replacement may contain special character (&) or escapes (\1 through \9) to refer to the corresponding matching sub-expressions in the “find” regular expression.

To find text in a file and output to a different file with the replacement the command is:

sed 's/find/replace/g' original.php > replaced.php

In the last command if you do not specify the output filename, it will simply show the file content on the screen with replaced string. There’s another command (similar to “sed”) which can be used for the same purpose is from perl.

perl -pi -e 's/find/replace/g' original.php

This command will find the word “find” and replace with the word “replace” in original.php. For this command “-p” option assume a loop like “while (<>) { …. }” (which is similar to the option -n but it prints the lines as well). The following option “i” performs the same task as it does for “sed”. Then “-e” says anything after it is a online of program. According to the manual several “-e program” can be used.