sed command in Linux with Examples

The sed command is a stream editor for filtering and transforming text. In this tutorial, How to sed command in Linux with Examples.


sed [OPTION]... {script-only-if-no-other-script} [input-file]...

On the man page, the describes it

  • sed – modifies lines from the specified File parameter according to an edit script and writes them to standard output.
  • man sed – More details information about the sed command.
sed command in Linux with Examples

The sed command in Linux with Examples

For example, file sed_test.txt as below

[huupv@DevopsRoles vagrant]$ cat sed_test.txt                                                                                                                                  
# /etc/ntp.conf, configuration for ntpd; see ntp.conf(5) for help

driftfile /var/lib/ntp/ntp.drift

# Enable this if you want statistics to be logged.
#statsdir /var/log/ntpstats/

statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

# Specify one or more NTP servers.

# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board
# on 2011-02-08 (LP: #104525). See for
# more information.
pool iburst
pool iburst
pool iburst
pool iburst

Append line with sed command

$ sed '/^pool 3/ a server' sed_test.txt

Insert line with sed command

It will be added lines before the matching line.

$ sed ' /^pool 3/ i server' sed_test.txt

Delete line with sed command

used d to delete matching lines. \s is escaped for regular expressions.

$ sed ' /^pool\s[0-9]\.ubuntu/d' sed_test.txt

How to write multi-line sed command

There are two ways, use {} or other files.

Use {}

$ sed ' {
 /^pool 0/i server
 } ' ./sed_test.txt

create a ntp.sed file and read with -f option.

The content ntp.sed file.

/^pool 0/ i server prefer

The explain the above line.

/^$/d - Delete blank lines.
/^\s*#/d - Delete the line following # after any space including 0 (Delete comment line of #)

As a result

$ sed -f ntp.sed sed_test.txt

The backup file before changing the original file has been modified.

$ sed -i.bak -f ntp.sed ntp.conf


sed command is a simple command in Linux. It uses the number of lines of files. Thank you for reading the DevopsRoles page!


About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.