The sed command is a stream editor for filtering and transforming text. In this tutorial, How to sed command in Linux with Examples.
Syntax
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.

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 http://www.pool.ntp.org/join.html for # more information. pool 0.ubuntu.pool.ntp.org iburst pool 1.ubuntu.pool.ntp.org iburst pool 2.ubuntu.pool.ntp.org iburst pool 3.ubuntu.pool.ntp.org iburst
Append line with sed command
$ sed '/^pool 3/ a server ntp.devopsroes.com' sed_test.txt
Insert line with sed command
It will be added lines before the matching line.
$ sed ' /^pool 3/ i server ntp.devopsroles.com' 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 ntp.devopsroles.com
/^pool\s[0-9]/d
} ' ./sed_test.txt
create a ntp.sed file and read with -f option.
The content ntp.sed file.
/^$/d /^\s*#/d /^pool 0/ i server ntp.devopsroles.com prefer /^pool\s[0-9]\.ubuntu/d
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
Conclusion
sed command is a simple command in Linux. It uses the number of lines of files. Thank you for reading the DevopsRoles page!