We can use the sed stream editor provided by linux to filter and convert text line by line.

Options for sed command

Here are some options for sed commands.

Options

Option Meaning
-n or ‑‑quiet or ‑‑silent Ignore the automatic output.
-e script or ‑‑expression=script Add the script.
-f script-file or ‑‑file=script-file Add the script-file’s content.
-r or ‑‑regexp-extended Use extended regular expressions.

Commands

Zero- or One- address commands

Command Meaning
a \text Append text after the specified lines.
i \text Insert text before the specified lines.
r filename Append text from filename.

Commands with accept address ranges

Command Meaning
c \
d Delete matching lines.
p Output matching lines.
s/regexp/replacement/ Replace the content that the regexp matches with the content of the replacement, append g at the end means match globally, append i at the end means to ignore case.
w filename Write the specified content to filename.

Addresses

Address Meaning
number Match the specified line number.
first~step Match every step line starting with line first.
$ Match the last line.
/regexp/ Output lines matching the regular expression.
addr1,addr2 Output the contents from lines addr1 to addr2.
addr1,-N Output the contents from lines addr1 to N lines.

Examples

Before we get started, let’s prepare some test content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
printf '%s\n' \
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nisi tellus,' \
'egestas sed dolor nec, eleifend venenatis mi. Mauris ac ligula' \
'scelerisque libero interdum varius. Aenean nec arcu nec turpis' \
'commodo mollis. Morbi suscipit felis libero, eu sollicitudin justo' \
'condimentum id. Praesent eu metus rutrum, varius leo malesuada,' \
'varius sapien. Vestibulum blandit, dolor bibendum bibendum ultricies,' \
'ipsum velit pretium arcu, eu maximus augue massa vitae justo. Etiam' \
'elit sapien, placerat quis libero a, tincidunt ornare erat. Praesent eu nibh' \
'ac sem mattis tincidunt. Aliquam erat volutpat. Nulla egestas dui ac urna' \
'convallis, vel egestas lectus ultrices. Morbi sit amet quam eget tortor' \
'laoreet laoreet id non libero.' > sed_file

Match From Line One to Line Five

1
sed -n '1,5p' sed_file
img

Match The Last Line

1
sed -n '$p' sed_file
img

Append Lines After Line One, Two and Three

1
sed '1,3a \A Line After Line One, Two and Three' sed_file
img

Insert A Line Before Last Line

1
sed '$i \A Line Before Last Line' sed_file
img

References sed, a stream editor, SED(1)

Buy me a coffeeBuy me a coffee