Find and replace a text in a file using Unix SED command

SED command stands for stream editor and it helps to perform lot of functions in files like searching,replacing,insertion or deletion.We can find and replace the particular text without opening the file using SED command.

SED command syntax

Explanation

sed = Stream EDitor
-i = in-place (i.e. save back to the original file)

The command string:
s = the substitute command
original_text = a regular expression describing the word to replace (or just the word itself)
new_text = the text to replace it with
g = global (i.e. replace all and not just the first occurrence)

file.txt = the file name

Lets consider the file sample.txt as below

There are many useful commands present in the unix.
The unix is one of the popular operating system in the world.

Example

Output :
There are many useful commands present in the linux.
The linux is one of the popular operating system in the world.

The original string unix is replaced with the new string linux in the file sample.txt using the sed command.sed command has the lot options to perform the file operation like this.


Chang the delimiter slash(/)

We can use different delimiters other than slash in the sed command.Lets consider you want to change the web url to another url a

Since the url contains slash, we can specify the different delimiter as underscore(_) or pipe(|) symbol in the sed command.Questions:

How to use the variable names in the sed command?

  • Here the new_user is a variable and it contains the value as “Michael”.sed command used to replace the user to Michael in the file.txt.
  • You have to use double quotes for that sed command would expand the variables.
  • If the original or new string contains slash(/),you can use different separator.