Intro

sed is stream editor, a command line used to perform basic text transformation, usually on a file.

Running sed

sed -OPTIONS 'SCRIPT BLOCK' /path/to/your/file

sed options

“Important” options for sed will be listed below:

-n / --quiet / --silent

Suppress automatic printing of pattern space

--debug

Annotate program execution. This will output the sed program in slightly user readable way

-i / --in-place

Edit files in place

-i[SUFFIX] / --in-place[=SUFFIX]

Backup file with SUFFIX supplied, and then edit file in place

-E

Use extended regular expressions in the script.

Exit Status

0

Successful

1

Invalid script block

2

One or more input file specified could not be opened

4

I/O error or serious processing error during runtime

Sample

# Run sed with input from pipeline
echo 1 | sed '\%1%s21232'

# Print exit status
echo $?

Script block

Syntax model

[addr]x[options]

Addressing – Lines

# Script below denotes line 30 to 35
sed '30,35(x)[options]' path/to/your/file

Addressing – from line number until first encounter

# Script below denotes line 1 until first regexp
sed '1,/^regexp/(x)[options]' path/to/your/file

Addressing – Last line

# Script below denotes last line
sed '$ (x)[options]' path/to/your/file

Options – Append after certain line

# Script below append 2 lines of "The quick brown fox"
sed -i '$ a \
The quick brown fox \
The quick brown fox' path/to/your/file

$ seq 5 | sed '$ a Test'
1
2
3
4
5
Test

Options – Prepend before certain line

# Script below prepend 2 lines of "The quick brown fox"
sed -i '1 i \
The quick brown fox \
The quick brown fox' path/to/your/file

$ seq 5 | sed '$ i Test'
1
2
3
4
Test
5

Options – Replace

# Script below replace line(s) with text
sed '(addr)c "Replace with"'

$ seq 5 | sed '2,3c Yellow'
1
Yellow
4
5

Sample

Commenting Line

# Comment line from text file that start with "aaa aaaaa"
sed -i '/^aaa aaaaa/I s/^#*/#/' path/to/file

Append lines to file

# Add new ufw config
sed -i '$ a \
[ZeroTier Custom] \
title=ZeroTier Custom \
description=Custom port for this server \
ports=29994/udp|61231/udp' /etc/ufw/applications.d/ufw-zerotier

Append text to line in file

# Change the above line, adding port 51111/udp
sed -i '/^PORTS=29/Is/$/|51111\/udp/' /etc/ufw/applications.d/ufw-zerotier

Resources

GNU sed live editor

Last modified: 14 January 2022