How to update file content using Sed command: A comprehensive guide:

Sed stands for stream editor is a powerful editing tool in Linux, used in text manipulation. It can search and replace the text in the file and can also be used to delete and append the files. Let’s take an example of a file containing the list of customers having their names, city in which they are located and other such details. Now we want to edit the city details to something else then we can change the content of the file using the sed command.

Here is the syntax of sed command:

sed [options] script filename

Basic Search and replace with sed command:

Lets take an example that we have a file with name file.txt and we want to replace the content of the file using sed command.

To see the content of the file we can use the cat command:

cat file.txt
Output:-

Hello World
Welcome to the World

Now in this file we want to replace the word “World” with “Linux_World”. We can do the needful using the following command:

sed 's/World/Linux_World' file.txt

Now let’s break down the command:

  1. s stands for substitute
  2. Then comes the word that we are searching for which is “World” in our case
  3. After that we add the word with which we want to replace.
  4. / is used to separate the components of the command

Replace all the occurrence in a line:

The above command will only replace the first occurrence of the pattern in each line. If we want to replace all the occurrences then in that case we have to use g flag which stands for global:

sed 's/World/Linux_World/g' file.txt

Edit the file directly:

The commands before will edit the word and display the output directly on the screen. If we want to edit the file directly i.e to make the changes in the file then in that case we can use –in-place option or -i option to make the changes take effect.

sed 's/World/Linux_World/g' file.txt --in-place

OR

sed -i 's/World/Linux_World/g' file.txt

Create the backup of file while editing:

If we want to create the backup of file while editing then we can use bak word along with the -i flag

sed -i.bak 's/World/Linux_World/g' file.txt

Some other Useful cases of Sed:

Below are some cases of the sed command:

We can edit the specific lines as well using the sed command.

sed '1s/Hello/Hi/' example.txt

The above command will replace the “Hello” with “Hi” only on the first line of the file:

sed '$s/Hello/Hi/' file.txt

The above command will replace the Hello with hi on the last line.

sed '1d' file.txt

The above command will delete the 1st line of the file.

sed '$d' file.txt

The above command will delete the last line of the file.

Hope after reading this article you got the basic understanding of the sed command. In order to learn more about Linux do visit our site simplealltech.com. Happy learning.

Leave a Comment