Unix replace string in file

Question:
How to replace text string in a Unix file

A string can be replaced within a unix file using the 'sed' command. For example, it may that you've created a MySQL dump and you want to update a string and then import it back into the database.

For example, let's say we have a string '/var/www/vhosts/intranet2' within a file named 'intranet.sql' and we want to replace it with '/var/www/vhosts/intranet' and save it into a new file named 'intranet-updated.sql'.

You simply need to enter:

  sed 's/\/var\/www\/vhosts\/intranet2/\/var\/www\/vhosts\/intranet/g' intranet.sql > intranet-updated.sql

i.e. sed 's/{string-to-find}/{replacement-string}/g {original-file-name} > {new-file-name}

Please note:

  • s - stands for subsitution
  • \ - is the backslash used to quote the slash in the path name.
  • the g is used to signify global replace, otherwise only the first instance will be replaced

Here are two more examples:

The following will output the word "night"

  echo day | sed s/day/night/

The following will output the word "Sunnight"

  echo Sunday | sed 's/day/night/'
Taxonomy: