sed append

Introduction

With sed append you can add entries to files

To use the sed append command you need the 'a' option

The general syntax looks like this:

sed '[range] a string_to_append' file

Translation

sed ' [range] a characters_to_append' file

range is the area in which the replacement should be made. It is specified by a condition, that is, it indicates a pattern or sample. It must always be inside / /

string_to_append are the characters that need to be appended to the file

file is the name of the file (can include the path to the file) in which this replacement will be made

Example

Let's look at the file sites.txt

cat sites.txt

Aviasales Travel
Booking.com Hotels
Hotellook Hotels

Let's add after the line Booking.com Hotels the line: eth1.ru IT

sed '/^B/ a eth1.ru IT' sites.txt

Aviasales Travel
Booking.com Hotels
eth1.ru IT
Hotellook Hotels

append does not change the contents of the file. Run it again

cat sites.txt

Aviasales Travel
Booking.com Hotels
Hotellook Hotels

The file has not changed

In the very same command, replace a with i (insert - to insert)

Aviasales Travel
eth1.ru IT
Booking.com Hotels
Hotellook Hotels

Now the new line has become higher than the pattern. The file still does not change.

If you use Ubuntu run

sed -n 'p' /etc/ntp.conf

And find lines there of the form #pool 0.ubuntu.pool.ntp.org

You can make sure they are there with the command

sed -n '/ubuntu/p' /etc/ntp.conf

#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 pool ntp.ubuntu.com

You can delete lines of the form #pool 0.ubuntu.… with the command

sed '/^#pool\s[0-9]\.ubuntu/ d' /etc/ntp.conf

I remind you that \s means one space

[0-9] means one arbitrary digit

Add text to the end of a file

To add the text TEXT to the end of the file file use the command

sed -i -e '$aTEXT' file

The file must not be empty initially

The same command in a Make file will look like this

.PHONY: addtoend addtoend: @sudo sed -i -e '$$aTEXT' file

If you need to add text after every line of the file, run

sed -i -e 'aTEXT' file

Article author: Andrei Olegovich

Banner image