Replace text in a file using SED in Linux

Home > Search
  by

The sed command with the s (substitue) option can be used to change text in a file or a variable. Let's say that file.txt contains the text Hello World.

Hello World

 

The sed command with the s (substitute) flag is used to replace data. In this example, the text "Hi" will be replaced with the text "Hello". It is also important to recongize that when no options are used, the text in the file will not be changed. Instead, the result will simply be displayed in the terminal. 

~]# sed 's/Hello/Hi/' file.txt
Hi World

 

The -i or --in-place option will actually change the content of the file.

~]# sed -i 's/Hello/Hi/' file.txt

 


Replace multiple instances of a string (global)

If a file contains more than one occurence of a string, the g (global) option will need to be used to change every instance of the string. For example, let's say a file contains the following text.

Hello World
Hello World
Hello World

 

If the g (global) flag is not used, only the first instance of the word Hello will be changed.

~]# sed 's/Hello/Hi/' file.txt
Hi World
Hello World
Hello World

 

The g (global) flag will change every instance of Hello to Hi.

~]# sed 's/Hello/Hi/g' file.txt
Hi World
Hi World
Hi World

 


Delete

The d flag can be used to delete lines in a file.

~]# sed -i '/Hello World/d' file.txt

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments