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 'length > 120' finds the lines that are too long

Awk
~/tips/tip-awk-length-long-lines

awk 'length > 120 {print FILENAME ":" FNR ": " length}' *.py

Lists every line above a certain length with file name and line number.

Style checks, broken CSV rows and minified code hiding in a source file all show up as lines that are much longer than the rest. awk can find them across a whole set of files.

awk 'length > 120 {print FILENAME ":" FNR ": " length}' *.py

length without parentheses is the length of the current line. FILENAME is the file being read and FNR the line number within that file, so you get output like app.py:42: 131, the same shape that editors and grep use.

To see the single longest line of a file, I’d keep track of the maximum:

awk 'length > max {max = length; line = FNR} END {print line, max}' data.csv

A note on what length counts. gawk counts characters if your locale is UTF-8, so an accented letter counts as one. mawk and some other awks count bytes, which makes lines with emoji or accents look longer than they are. For ASCII text that difference doesn’t exist.

Tabs count as one character too, though an editor may show them as four or eight columns. And on standard input, FILENAME is empty in some awks and - in others, depending on the implementation.

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