brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: sed -n '10,20p' prints just a range of lines from a file

Sed
~/tips/tip-sed-print-line-range

sed -n '210,218p' /etc/nginx/nginx.conf

Prints only the lines between two line numbers, without opening an editor.

An error message says the problem is on line 214 of a config file, and you just want to see that bit. Opening an editor is overkill, and head piped into tail works but makes you do arithmetic.

sed does it in one go. -n switches off sed’s habit of printing every line, and the p command prints only the lines in the address range you give it:

sed -n '210,218p' /etc/nginx/nginx.conf

That shows lines 210 up to and including 218, nothing else. A few variations I’d keep in mind:

sed -n '214p' file.conf      # one line
sed -n '200,$p' file.conf    # from line 200 to the end
sed -n '214,+5p' file.conf   # line 214 and the 5 after it

The $ stands for the last line. The ,+5 form is a GNU extension, so it works on Linux and in the Unraid terminal but not with the BSD sed that ships with macOS. On my MacBook I’d stick to the plain first,last form, which works everywhere.

One caveat with huge files: sed keeps reading after the range ends, because it doesn’t know you’re done. On a log of several gigabytes, add a quit command after the last line you want: sed -n '210,218p;218q' big.log. Also, if the first number is bigger than the second, sed prints only that first line instead of an error, so a typo there can look like an almost empty file.

Further reading: GNU sed manual

More Sed tips sed -n '$=' access.log echo 'hello world' | sed 's/.*/\U&/' printf 'key=1\nport=80\n' | sed '/^port=/a timeout=5' sed 's/\/mnt\/user\/appdata\/old/\/mnt\/user\/appdata\/new/' app.conf sed -i.bak 's/old-host/new-host/g' config.txt All Sed tips (6) All topics

Link