Skip to content

sed

general usage
sed 'instruction' <input
sed 'instruction1; instruction2' <input
sed -e 'instruction1' -e 'instruction2' <input
sed -f instruction-file <input                  # instructions from file
sed -e 'instruction' -f instruction-file <input # instructions from arg and file
sed -i 'instruction' <input                     # in file editing
sed -i'.backup' 'instruction' <input            # in file editing with backup
sed -n  'instructions' <input                   # disable auto print
sed -s 'instructions' file1 file2               # restart stream with each file
addressing
sed '5a text' <input                # append line after line 5
sed '10,13d' <input                 # delete lines 10-13
sed '0,5!s/pattern/text/g' <input   # substitute all matches except for line 0-5
sed '/pattern/i text' <input        # insert line before matching line
sed '/pattern/!i text' <input       # insert line before all lines not matching
sed '/p1/,/p2/c text' <input        # replace lines matching p1 to p2 with text
sed '10,/pattern/d' <input          # delete lines from line 10 to matching line
sed '/pattern/,+5p' <input          # print matching line plus next 5 lines
sed '0~25r file' <input             # append content of file to each 25th line
sed '10,+80y/ab/AB/' <input         # replace characters from line 10 to 90
sed -n '$p' <input                  # print last line
a - append line after matching line
sed '/pattern/a text'
i - insert line before matching line
sed '/pattern/i text' <input
r - append file content after matching line
sed '/pattern/r filename' <input
c - replace matching line
sed '/pattern/c text' <input
d - delete matching line
sed '/pattern/d' <input
s - substitute matching line
sed 's/pattern/text/' <input        # 1st match
sed 's/pattern/text/g' <input       # all matches
sed 's/pattern/text/3' <input       # 3rd match
sed -n 's/pattern/test/p' <input    # print matching line
y - substitute characters on current line
sed 'y/abc/ABC/' <input
p - print matching line
sed -n '/pattern/p' <input
e - execute matching line as command (and replace)
sed '/pattern/e' <input
w - write macthing line to file
sed '/pattern/w file' <input
grouping commands
sed '1,5{ /^$/d ; s/pattern/text/ }; 10,15{ s/pattern/text/ }' <input
use extended regex
sed -r 's/  s+//g' <input
reference match pattern &
sed 's/[fb]oo/-->&<--/' <input
reference match group (1-9)
sed 's/  ([a-z]*  ).*/  1/' <input
custom separators
sed 's_pattern_text_' <input
sed 's:/path:/new/path:' <input
sed '/pattern/=' <input
instructions from file with variables
sed -f <(var1='test' envsubst '$var1' < sed-script.sed) file
useful examples
sed 's/^<foo>\(.*\)<\/foo>/\1/' <input      # remove sourrounding xml tag

last updated: Sat Aug 12 14:29:24 2023

Back to top