Linux: Find & Replace the String in any file

This item was filled under [ General, Linux ]

It is very difficult to find each word and then replace it with the desired one. In a long file, replacing wrong entries is pretty tough. In this case sed command proves to be useful.
General syntax for the sed command

sed -i a/expression/replacement/g myfile.txt

Here i is used to insert
s is used to substitution
expression is what to find
replacement is what to replace
g is used for space

If we want to find a string with the filename “jack” for instance, and want to replace it with string“jacky”, then in this case the command will be:

sed -i s/jack/jacky/g myfile.txt

If we want to take a backup of that file before the replacement, then use the -backup option.

sed -ibackup s/jack/jacky/g myfile.txt

If we want to replace one string with another in the file, then we can also use the replace command like sed. Following is the syntax of the command.

replace source destination
outputfile

Suppose we want to replace ‘jack’ with ‘jacky’.Then the command would be:

replace jack jacky file2.txt

Note: The command always create a new file with the new replacement.

  • Share/Bookmark
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Comment

  • Google Translator

      Translate to: