Replace, change, or update data in a file using the SED command in Linux

Home > Search > Linux commands
  by

The sed command with the s (substitue) option can be used to change text in a file. For example, let's say that file1 contains the text Hello World.

~]# cat file1.txt
Hello World

 

In this example, the sed command replaced the word Hello with Hi.

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

 

The prior example will only show the change in the Terminal, and will not actually change the contents of the file. The -i option will change the content of the file.

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

 


Change every instance of a word

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

~]# cat file1.txt
Hello World Hello World Hello World

 

If the g option is not used, only the first instance of the word Hello will be changed.

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

 

The g option will change every instance of Hello to Hi.

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

 


Change certain instances of a word

Let's say that file1 contains the text Hello World Hello World Hello World.

~]# cat file1.txt
Hello World Hello World Hello World

 

The g option followed by an integer will only change some instances of a word. In this example, every instance of the world Hello starting and the second instance and beyond is changed to the word Hi.

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

 


Remove text from a file

In this example, the word Hello is removed from file1.

~]# sed '/old/g' file1.txt

word

word

 

Let's replace the word "old" with the word "new" on lines 3 through 5.

~]# sed '3,5s/old/new/g' file1.txt
old
word
new
word
new

 

Let's double space the file.

~]# sed G file1.txt
old

word

old

word

old

 

Count the number of lines in the file (The NL command or cat -n is much easier).

~]# sed -n '$=' file1.txt
5

 


Following are a list of frequently used sed commands.



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