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: awk '/START/,/END/' prints the lines between two markers

Awk
~/tips/tip-awk-range-pattern

awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/' bundle.pem

Prints a block of lines from one matching line up to and including another.

Pulling one block out of a bigger file, like one certificate from a bundle or one section from a log, is a job for a range pattern.

awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/' bundle.pem

Two patterns separated by a comma make a range. awk starts printing at the first line that matches the first pattern and stops after the line that matches the second. Both marker lines are included. With START and END markers, the output is the START line, the lines in between and the END line.

If you want the lines in between without the markers, I’d use a flag rather than a range:

awk '/END/ {f=0} f; /START/ {f=1}' file.txt

The order of the three parts does the trick: the END line switches the flag off before it can be printed, and the START line switches it on after the print check.

Ranges repeat, which is what you want for a bundle with many certificates: every block is printed. If an end marker is missing, the range just runs to the end of the file. And if the start and end pattern match the same line, the range is that one line only, because awk checks the end pattern on the starting line too.

Further reading: GNU awk manual, POSIX awk specification

More Awk tips echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' awk -F, 'NR>1 {print > ($2".csv")}' data.csv echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}' echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}' echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}' All Awk tips (17) All topics

Link