Bash Sed Addressing
Sed addressing is the way to pick which lines a sed command touches. An address can name one line, a range of lines, or a pattern, and lines outside the address stay unchanged.
One line, then a line range
The -n option hides every line except the ones p prints. The first run prints line 2 only, and the second run prints lines 1 through 3.
printf 'one\ntwo\nthree\nfour\n' > lines.txt
sed -n '2p' lines.txt
sed -n '1,3p' lines.txtA range between two patterns
The range starts at the line holding start and ends at the line holding end. The line after end falls outside the range, so it stays hidden.
printf 'start here\nmiddle line\nend here\nafter end\n' > block.txt
sed -n '/start/,/end/p' block.txtDelete addressed lines
The pattern run drops every line holding remove me and keeps the rest. The number run drops line 2 from the short file and keeps lines 1 and 3.
printf 'keep one\nremove me\nkeep two\nremove me\nkeep three\n' > keep.txt
printf 'one\ntwo\nthree\n' > nums.txt
sed '/remove me/d' keep.txt
sed '2d' nums.txtEdit in place with a backup
The -i.bak option edits the file itself and saves the original as a backup. The first two lines show the edited file, and the last two lines show the backup content.
printf 'old value\nold value\n' > notes.txt
sed -i.bak 's/old/fresh/g' notes.txt
cat notes.txt
cat notes.txt.bakExample
printf 'header line\nstart section\ntask one\ntask two\nend section\nfooter line\n' > doc.txt
sed -n '/start section/,/end section/p' doc.txt
sed '$d' doc.txtKey points
- Line address: a number like 2 picks exactly that line.
- Range: 2,4 picks lines 2 through 4.
- Pattern range: /start/,/end/ picks from the first matching line to the second.
- -n with p: prints only addressed lines and hides the rest.
- d: deletes addressed lines from the output.
- -i: edits the file itself instead of printing a changed copy.
- Backup suffix: -i.bak keeps the original file under a .bak name.
In this example, the script first creates a small document. The pattern range run prints only the section, from its start line to its end line. The $d run then prints the whole document minus its last line, so the footer drops out.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which sed command prints only lines 2 through 4?