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 '$1=$1' with OFS turns spaces into commas

Awk
~/tips/tip-awk-ofs-dollar1-rebuild

printf 'a b c\n' | awk -v OFS=, '{print}' # a b c

Rebuilds every line with a new field separator, for turning aligned output into CSV.

Setting OFS, the output field separator, looks like it should change the output. On its own it does nothing, and that confuses people.

printf 'a b   c\n' | awk -v OFS=, '{print}'          # a b   c
printf 'a b   c\n' | awk -v OFS=, '{$1=$1; print}'   # a,b,c

awk keeps the original line in $0 as long as you don’t touch a field. Only when a field is assigned does awk rebuild $0 from the fields, joined with OFS. $1=$1 changes nothing about the value, but it forces that rebuild. As a side effect, runs of spaces collapse into one separator, which is exactly what you want when turning aligned command output into CSV:

df -P | awk -v OFS=, '{$1=$1; print}' > df.csv

You’ll also see the short form awk '{$1=$1}1', where the 1 is a condition that’s always true and prints the line.

This isn’t a real CSV writer though. A field with a comma in it, or a column that contains spaces like a file name, ends up split or mixed up. For df output with mount points that contain spaces, I’d check the result before importing it anywhere.

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