How to Use Sed in Linux

Sed stands for stream editor. It is a command line based editor for Linux. Popular use of sed is for editing file(s) as part of an automation script in Linux, as usual editors require active user input and cannot edit files outside of the editor screens. Sed is most commonly used for doing a find and replace from the command line.

This type of text editor can also be categorised as a non interactive text editor.

Let us see some common options to edit files using Sed. We will take the following file as example:

$: cat test.txt A quick brown dog jumped over the lazy cat. Linux Operating System. The Forest near my place has a cat as well as wolves.
Code language: JavaScript (javascript)

Search and Replace

To search for a string in a file and replace with another string, run:

sed -i "s/cat/fox/g" test.txt
Code language: JavaScript (javascript)

Here, the -i flag instructs sed to write the changes to the file. Without this flag, sed will just display the file with the changed string.

In the quotes, we have s/cat/fox/g. The s is for the search and replace command of sed. Then we have the string to be searched, which is cat. Then the string to replace it with, i.e., fox. Finally, we have the optional g, which instructs sed to replace all occurences on all lines of the file. Without the g, sed will replace only first occurrence of cat on every line.

Regex can be also used here.

sed -i "s/f[a-z]*\./cat\./g"
Code language: JavaScript (javascript)


To insert text before a line with a matched string, use:

sed -i "/cat/i Start:" test.txt
Code language: JavaScript (javascript)

Here, cat is the searched string and Start: is the string to enter before the line where the searched string is found.

Similarly, to insert text after a line, use:

sed -i "/fox/a End." test.txt
Code language: JavaScript (javascript)


To delete a line with containing a substring, use:

sed -i "/Linux/d" test.txt
Code language: JavaScript (javascript)

To delete a line with line number, eg. the first line, use:

sed -i '1d' test.txt
Code language: JavaScript (javascript)

Combining multiple functions

To combine multiple functions, eg. search and replace, delete, in one command, -e flag can be used.

sed -i -e "s/fox/cat/g" -e '2d' test.txt
Code language: JavaScript (javascript)

🍻 Cheers!