[How To] Replace A String With Another In Unix

[ Unix ] Replacement of a string with another uning sed

As we have been seeing from the last few posts the raw power of sed, we will be continuing it in our today's post.
Substitution of a specific character in a file is what we will learn in today's post.
Suppose we have the following file with multiple occurrences of the word 'night' in the file.


This is a great night.
The party was in night, at around 10.
The night was cold and dark.
We had great fun.

And suppose our requirement is to replace or substitute all occurrences of the string 'night' in night.txt with the string 'day' and create a new file day.txt. This can be done with the help of following command.

$ sed 's/night/day/' < night.txt > day.txt
$ cat day.txt

This is a great day.
The party was in day, at around 10.
The day was cold and dark.
We had great fun.

Let us now understand the command: the s in the beginning is for substitution. The next parameter 'night' is the string to be replaced, followed by the replacement string ie. 'day'. The input redirection operator < takes in the file night.txt as input to the Stream Editor. The output redirection operator > gives the output of the sed command to a new file day.txt in the same directory.

Another way to achieve this is through vi editor directly. The substitute (%s) command in vi editor can replace all occurrences of a particular string with another. However, it saves the changes in the same file and there is no option to redirect the output.

Following is the syntax after opening vi editor..


...and you are done :)