sed command in Linux with Examples

The sed command is 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]...

In man page the describe 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

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 aways, 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

Backup file before change the original file has been modified.

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

,

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 DevopsRoles.com 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 *

Comment moderation is enabled. Your comment may take some time to appear.

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