How to replace words/strings in multiple files using sed.

sed - stream editor for filtering and transforming text

The streamline editor (sed) is very useful command for searching and replacing string/texts in multiple files.

Example 1

/var/named/# sed -i ’s/127.0.0.1/192.168.0.0.1/g’ *.com.db

Example 2

s/regexp/replacement/

Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special char?acter & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expres?sions in the regexp.

In the above command

sed -i is used to for editing.

s is used for subsituite the following text/word.

127.0.0.1 is the string to be replaced.

192.168.0.0.1 is what you would like replace with.

g is used for global search, looking for occurrence of text in all the lines in file.

To replace string 127.0.0.1 with 192.168.0.0.1 in multiple files using sed editor run sed like this :

$ sed -i ’s/127.0.0.1/92.168.0.0.1/g’ *.com.db

In Linux and UNIX sed command is available with default installation.

sed could show me only (say) lines 12-18 of a file and not show me the rest. This was very handy when I needed to review only part of a long file and I didn’t want to alter it.

# the ‘p’ stands for print
sed -n 12,18p myfile

Reference : http://sed.sourceforge.net

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.