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.
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
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"
Insert
To insert text before a line with a matched string, use:
sed -i "/cat/i Start:" test.txt
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
Delete
To delete a line with containing a substring, use:
sed -i "/Linux/d" test.txt
To delete a line with line number, eg. the first line, use:
sed -i '1d' test.txt
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
🍻 Cheers!
Member discussion