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 RS="" reads text in blocks separated by blank lines

Awk
~/tips/tip-awk-rs-paragraph-mode

awk 'BEGIN {RS=""} /[email protected]/' contacts.txt

Treats each paragraph as one record, so you can filter whole blocks instead of single lines.

Some files are made of blocks: address lists, dpkg -s output, ini-style records separated by a blank line. Searching them line by line loses the context.

Setting the record separator to an empty string switches awk to paragraph mode. Every block between blank lines becomes one record:

awk 'BEGIN {RS=""} /[email protected]/' contacts.txt

That prints the whole block that contains the address, not just the matching line. That gives the name and the mail line together.

I like it even more when you also set the field separator to a newline, so each line of the block is a field:

awk 'BEGIN {RS=""; FS="\n"} {print $1 " | " $2}' contacts.txt

Now $1 is the first line of every block and $2 the second, which turns a block file into one line per record.

Lines that contain only spaces don’t count as blank in paragraph mode, so a block that “looks” separated may still be glued to the next one. Clean those up first, for example with sed 's/^[[:space:]]*$//'. And several blank lines in a row count as one separator, so you won’t get empty records.

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