sed Address Ranges: M,N and /a/,/b/
A sed range, written start,end, runs a command on every line from the start address through the end address.
Ranges extend addressing to spans. Two numbers, two regexes, or a mix let you edit a whole block such as one section of a YAML file.
What it does
A range address is two addresses joined by a comma. The command runs from the line matching the first through the line matching the second. With regex endpoints, sed matches the first start, then the next end after it.
Common usage
sed '2,8d' file # delete lines 2-8
sed '/^\[db\]/,/^\[/s/host=.*/host=prod/' app.ini # within [db] block
sed -n '/START/,/END/p' file # print the block
sed '/^server:/,$d' config.yml # delete from server: to EOFOptions
| Range | What it spans |
|---|---|
| M,N | Line M through line N inclusive |
| /a/,/b/ | First line matching a through next matching b |
| M,/b/ | Line M through next line matching b |
| /a/,$ | First line matching a through the last line |
| M,+K (GNU) | Line M and the K lines after it |
| range! | Invert: apply outside the range |
In CI
Range editing is the cleanest way to touch one section of an INI or YAML file without a full parser. The M,N and /a/,/b/ forms are POSIX; the M,+K relative form is a GNU extension that fails on BSD sed.
Common errors in CI
If a regex range never closes, the command runs to end of file, often deleting more than intended; confirm the end regex actually appears. sed: -e expression #1, char N: unexpected `,' flags a malformed range such as a missing first address.