How to Use sed Command in Linux

Linux Sed command is a stream editor that can perform basic text transformation on input stream. It can be used for editing in shell scripts for non-interactive editing. Other command line editors like vi, nano or emcs are big text editors, and these cannot be used for non-interactive editing.

Sed's ability to filter text in a pipeline particularly distinguishes it from other types of editors. This article explains sed stream editor with its various options.

The sed command is regular expression aware command, means it can understand the regular expressions provided to it.

1) Substitute

Sed can be used to find and replace a pattern on the input. Option 's' is used for replacing a pattern. The syntax of the command is:

$ sed 's///'

For example:

$ echo "Hello there" | sed -e 's/there/here/'
Hello here

Sed command replaces 'there' with 'here'.

By default, sed command replaces just first instance of pattern in a line. For example:

$ cat numbers.txt
one two three one

$ sed 's/one/four/' numbers.txt
four two three one

Here, 2 instances of 'one' exist in the file. But sed has replaced only the first one. If we want to replace all the instances of the pattern, we need to use the 'g' command of sed:

$ sed 's/one/four/g' numbers.txt
four two three four

2) Insert and Append

A pattern can be inserted to the file with 'i' command and appended with 'a' command. This insert and append operation use a newline for inserting and appending. The regular expressions need to be preceeded by a backslash.

$ sed 'i \inserted line' numbers.txt
inserted line
one two three one

$ sed 'a \Appended line' numbers.txt
one two three one
Appended line

3) Suppressing and printing output

By default, sed prints to standard output as you might have noticed. To run sed in quiet mode, -n option is used.

$ sed -n 's/one/four/' numbers.txt

When using the above option, to print the output p command is used.

$ sed -n 's/one/four/p' numbers.txt
four two three one

$ sed -n 's/one/four/gp' numbers.txt
four two three four

This can be useful to use sed like grep:

$ sed -n '/root/p' /etc/passwd

It finds the pattern root in the file /etc/passwd.

4) Deleting lines

sed can be used to remove lines from a file with d command:

$ cat count.txt

$ sed '1,3d' count.txt

The pattern '1,3d' tells sed to remove lines 1 to 3 from the given file.

5) Writing to a file

The w command can be used to write the output to a file, which is by default printed on the standard output. The w command requires a filename to which the output will be written.

$ sed -n '/root/w rootpwd.txt' /etc/passwd

$ cat rootpwd.txt

As we can see, the output is written to the file rootpwd.txt

Thanks for reading this article and please submit your comments below.

Bobbin Zachariah 8:57 am


Your email address will not be published. Required fields are marked *

All comments are subject to moderation.