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 NF removes empty lines, including the ones with only spaces

Awk
~/tips/tip-awk-nf-drop-blank-lines

awk NF file.txt > clean.txt

Drops every line that has no visible content, also lines with just spaces or tabs.

Config files, pasted text and exports are full of blank lines. Removing them is two letters with awk.

awk NF file.txt > clean.txt

NF is the number of fields on the line. On an empty line it’s 0, and on a line with only spaces or tabs it’s 0 too, because the default field separator ignores whitespace. A pattern of 0 is false, so those lines don’t get printed. Any line with at least one word has NF of 1 or more and stays. An empty line and a line of three spaces both go; only lines with text stay.

That’s the advantage over grep -v '^$', which only drops lines that are truly empty and keeps the ones with a stray space. The grep equivalent is grep -v '^[[:space:]]*$', which I find harder to type correctly.

Combined with stripping comments, it’s a nice way to read a config file:

awk '!/^[[:space:]]*#/ && NF' /etc/ssh/sshd_config

Note that awk keeps the lines exactly as they were, leading spaces included. And the trick depends on the default separator: with -F,, a line of only spaces has one field and is kept.

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