Cancel

Sed command in Linux

sed is a powerful text editor, which stands for stream editor. It does insertion, deletion, search and replace, or substitution from your given paragraph. It is good for data manipulation and text transformation.

Options

Options are the real power of the sed command. Here I’ll cover the most common options.

  • -n return number of lines.
  • -i.bak update the file and .bak means take a backup before any change in the file.
  • -e multiple matches with regular expression.
  • Flags:
    • s is a string.
    • g to find and replace all places or globally.
    • d to remove x number of lines.

I have created dummy content for you to test all the above options.

1
2
3
4
5
6
7
8
9
10
123 foo foo foo
bar
bar
Ubuntu
foo
bar
456
youtube
bar
bash...

Get options listed above and put them one by one to the following structure.

You have 3 options to run the sed command. In this article, I will be using option 1 most of the time but you are free to choose other options as well.

1
2
3
4
5
6
7
8
# option 1
sed [options] filename.txt

# option 2
cat filename.txt | sed [options]

# option 3
<ANY_LINUX_COMMAND> | sed [options]

You can either use find and replace with underscore _ or backslash /.

1
2
echo "http://example.com/index.html" | sed 's_example_google_' # option 1 with underscore
echo "http://example.com/index.html" | sed 's/example/google/' # option 2 with backslash (recommended)

I am going to use a backslash in the rest of the article.

To return a number of lines use -n option and p means paragraph. The following command will return the first line of the file.

1
sed -n '1p' filename.txt

To find and replace globally use g flag and s flag means string. The following command will replace foo with the zoo.

1
sed 's/foo/zoo/g' filename.txt

Take the above example and update the file using -i flag. The following command will replace foo with zoo and update the file too.

1
sed -i.bak 's/foo/zoo/g' filename.txt

To find and replace multiple matches use -e option. The following command will find and replace multiple matches.

1
sed -ie 's/bar/xyz/g; s/youtube/YT/g' filename.txt

To delete a line from the file using d flag with a number of x lines that you want to remove. The following command will remove only 3rd line from the given file.

1
sed '3d' filename.txt

To find all digits and replace them with something else. The following will return SOMETHING_ELSE instead of all digits.

1
sed -e 's/[0-9]/SOMETHING_ELSE/g' filename.txt