Skip to content

How to use sed to edit text in Linux

sed, also known as stream editor, is a commonly used text processing tool in Linux.

Basic Syntax

The basic syntax of sed is straightforward. The syntax is as follows:

sed [options] 'command' file
sed line_range pattern/RegExp/ file

Here, the command is the action that sed takes on each line of the file, and the file is the name of the file to be processed. The options are used to modify the behavior of sed.

d          Delete
p          Print the lines that match a pattern
a \string  Append a line
i \string  Insert a line
r          Append text after a line
w          Write to another file
s/pattern/string/    Search and replace (only the first match on each line)
s/pattern/string/g   Global search and replace

(1) Replace the third line of test.txt with “hello” and output:

#!/bin/bash
sed "3c hello" test.txt

(2) Replace the third line of test.txt with “hello” and save to the original file:

#!/bin/bash
sed -i "3c hello" test.txt

(3) Delete the first three lines of test.txt:

sed '1,3d' test.txt

(4) Delete the fourth line to the last line of test.txt:

sed '4, $d' test.txt

(5) Delete the lines that contain “hello”:

sed '/hello/d' test.txt

(6) Delete two lines after the fifth line:

sed '5, +2d' test.txt

(7) Append a line “world” after the line that starts with “hello”:

sed '/^hello/a world' test.txt

(8) Write the lines that contain “abc” to a file named b.txt:

sed '/abc/w b.txt' test.txt

(9) Replace the lines that start with “#” in /etc/fstab with “#*#”:

sed 's/^#/#*#/' /etc/fstab

(10) Use sed to remove color codes from the output that has colors:

sed "s,\x1B\[[0-9;]*[a-zA-Z],,g"

Conclusion

  • man sed
Feedback