sed addresses, ranges and commands

grep, sed & awk · Practical · 12 min

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:

  • d delete the line (it isn't printed).
  • p print the pattern space. sed prints every line automatically, so p is normally used with -n, which turns automatic printing off: sed -n '10,20p' prints only lines 10 to 20.
  • q quits: sed 5q is a fast head -n 5.
  • i\ text, a\ text, c\ text insert before, append after, or replace the line. GNU sed also accepts the one-line form a 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.

Check yourself

  1. What does sed -n '/start/,/end/p' print?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.gnu.org/software/sed/manual/sed.html#sed-addresses