S
tream Ed
itorsed
is a utility that allows us to edit a stream of data by replacing some existing text with the desired one.
sed -V
prints the sed
versionsed -h
prints a summary of the sed
commandsed 's|pattern to match|pattern to replace the matched pattern|'
/
instead of |
: sed 's/pattern to match/pattern to replace the matched pattern/'
/
or |
, or any other delimiter like :
; but there should always be three otherwise an error is raisedecho day | sed 's|day|night|'
produces night
sed
works on every line, one by one and acts on the first match (greedy)\d
does not work, use [0-9]
instead)
echo "abc 123 abc 456" | sed 's/[0-9][0-9]*/& &/'
outputs abc 123 123 abc 456
echo "abc 123 abc 456" | sed 's/[0-9]*/& &/'
outputs abc 123 abc 456
because [0-9]*
matches 0 or more characters and the start of line is a match; [0-9][0-9]*
matches a string only made up of digits+
character in the regular expression search, use -r
flag to signify extended regular expressions
echo "abc 123 abc 456" | sed -r 's:[0-9]+:& &:'
outputs abc 123 123 abc 456
\
&
can be used to refer to the matched pattern
echo "123 abc" | sed 's/[0-9]*/& &/'
gives 123 123 abc
\1
upto \9
(9 captured groups) to refer back to any matched group
echo ab1e | sed -r 's/([a-z]+)/\1\1/'
outputs abab1e
echo ab abe | sed -r 's/([a-z]+) \1/dup/'
outputs dupe
echo ab ae | sed -r 's/([a-z]+) \1/dup/'
outputs ab ae
-r
g
g
flag sed s/pattern/replacement/g
echo ab1e | sed -r 's/([a-z]+)/9/g'
outputs 919
I
echo abcABCaBc | sed 's/abc/1/gI'
outputs 111
-n
-n
nothing will be printedp
sed
to print the modified lines-n
together with p
will print only the lines where a match is foundprintf "abc\nABC" | sed -n 's/abc/1/p'
outputs 1
printf "abc\nABC" | sed 's/abc/1/p'
outputs 1\n1
-e
sed
commands sequentiallyprintf "Ah! How do you do good sir this fine evening?" | sed -e 's/e/E/g' -e 's/o/O/g' -e 's/E/e/'
outputs Ah! HOw dO yOu dO gOOd sir this fine EvEning?
E
back to e
\
like in a shell scriptsed 'num s/pattern/replace/
printf "abc\nABC\naBc" | sed '2 s/abc/replace/I'
abc
replace
aBc
sed '1,10 s/pat/rep/'
sed '10,20 s/pat/rep/'
sed '10,$ s/pat/rep/'
$
denotes the end, similar to other utilities in shellsed
has the ability to only apply the commands to lines that match a specific pattern using the sed /pattern/ command
syntax.
sed -n '/abc/ p
mimics grep
; the command we are asking sed
to execute is p
sed
is to print the columns header of a file on different lines
echo 'colA|colB|colC|colD' | sed -e 's/|/\n/g' | cat -n
where |
was the column delimiter
1 colA
2 colB
3 colC
4 colD
cat -n
prints the contents and the line numbers as well