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 '/start/,/end/p' prints the block between two lines on Linux

Linux
~/tips/tip-linux-sed-n-range-between-patterns

sed -n '/BEGIN backup/,/END backup/p' /var/log/app.log

Pull one section out of a config or log, from a start line to an end line.

When a file has sections, you often want just one of them: one block of a config file, or the part of a log between two markers. A sed range does that.

sed -n '/BEGIN backup/,/END backup/p' /var/log/app.log

-n turns off the normal output, and p prints only the lines in the range. The range starts at the first line that matches the first pattern and ends at the next line that matches the second, both included. After that, sed looks for the start pattern again, so a log with five backup runs gives you all five blocks.

For an INI style file, the end is simply the next section header:

sed -n '/^\[mysqld\]/,/^\[/p' /etc/mysql/my.cnf

That prints the [mysqld] section plus the header of the section after it. I do not mind that extra line when I am reading, but in a script you may want to drop it.

If the end pattern never matches, sed keeps printing until the end of the file. That can look like the range worked when it did not, so check the last lines of the output. Also note that the end pattern is only checked from the line after the start, so a line that matches both patterns does not close the range by itself.

Further reading: GNU sed manual: range addresses

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link