Addresses turn sed from global search-and-replace into a precise editor for config files and generated text.
Every sed command can be prefixed by an address that selects the lines it applies to:
- a line number
3, the last line$, or a regex/^#/; - a range
5,10,/BEGIN/,/END/(from a line matching BEGIN to the next matching END), or/start/,+2; !after the address negates it:/^#/!means lines that are not comments.
Useful commands besides s:
ddelete the line (it isn't printed).pprint the pattern space. sed prints every line automatically, sopis normally used with-n, which turns automatic printing off:sed -n '10,20p'prints only lines 10 to 20.qquits:sed 5qis a fasthead -n 5.i\ text,a\ text,c\ textinsert before, append after, or replace the line. GNU sed also accepts the one-line forma text.=prints the line number.
Commands can be grouped with braces: /^\[db\]/,/^\[/{ s/^port=.*/port=5433/ } changes port only inside the [db] section of an INI file.
A regex range starts on the first matching line and ends on the next line matching the end pattern; if the end pattern never matches, the range runs to the end of the input.
Example
printf '# settings\nname=demo\n[db]\nport=5432\n[web]\nport=8080\n' > app.ini
sed -n '2,3p' app.ini # name=demo / [db]
sed '/^#/d' app.ini # everything except the comment
sed -n '/^\[db\]/,/^\[/p' app.ini
# [db]
# port=5432
# [web]
# change port only inside the [db] section
sed '/^\[db\]/,/^\[/ s/^port=.*/port=5433/' app.ini | grep port
# port=5433
# port=8080
sed '1a\
# generated, do not edit' app.ini | head -2 # adds a line after line 1
sed -n '$=' app.ini # 6 (number of the last line)Remember
- Addresses: line numbers, $, /regex/, ranges a,b and negation with !
- sed -n plus p prints only the lines you select
- d deletes, q quits, i/a/c insert, append and change lines
Watch out for
- Using p without -n and seeing every selected line printed twice.