sed with examples
sed stream editor is a very useful utility to manipulate text like replacing patterns, replacing patterns on a certain set of lines etc. We have listed some examples and you might find it useful for text manipulation.
1) sed: How to print nth line of a file?
sed -n 2p /tmp/text (print line 2 of a file)
2) How to replace text in output (stdout only)?
sed -e ‘s/xxx/yyy/’ <file> (### wont replace file.. will just display)
3) sed: How to replace text in a file?
sed -i ‘s/xxx/yyy/’ <file> (### will do the replacement in file)
4) sed: How to do multiple replacements in one line?
sed -i ‘s/xxx/yyy/;s/abc/yyy/’ <files> (## multiple replacements)
5) sed: How to delete a line(s) using sed?
sed -e ‘4,7d’ <file> ### deletes line 4,7 of file
6) sed: How to replace a given set of lines?
sed -e ‘1,125~s/Jan/AAA/’ ### replace from line 1 to line 125
7) sed: How to add an extra line after each line?
sed G <file> # double space a file
8) sed: How to replace a given occurrence in a line?
sed ‘s/foo/bar/4’ # replaces only 4th instance in a line
9) sed: How to replace lines which contain a certain word?
sed ‘/check/s/foo/bar/g’ #### substitute “foo” with “bar” ONLY for lines which contain “check”
10) sed: How to print line with given line numbers?
sed -n ‘8,12p’ # print line 8-12
11) sed: Print first 10 lines of a file.
sed 10q #print first 10 lines of a file
12) sed: Groupings – How to swap words in a text?
$ echo “foo bar” |sed -r ‘s/(.*) (.*)/\2 \1/’
bar foo
-r is for extended regex
\1, \2 – matched groups are represented with backslash <number>
13) sed: How to print last 5 lines of a file?
$ cat x.py |sed -n ‘4,$p’
14) sed: Ignore updates in certain lines?
example: updates all lines except 5,6,7,8:
seq 10|sed -r ‘5,8!s/(.*)/\1 x/’
1 x
2 x
3 x
4 x
5
6
7
8
9 x
10 x