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 gsub() replaces every match in a line or in a single field

Awk
~/tips/tip-awk-gsub-replace-text

echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}'

Replaces all matches of a pattern in the line or in one chosen column, and counts them.

I reach for sed to replace text, but once a file has columns, awk is often the better fit. Its gsub can change one column and leave the rest alone.

echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}'
2: cost: 1.50 and 2.25

gsub(regex, replacement) works on the whole line, replaces every match, and returns how many it replaced. sub does the same for the first match only. Add a third argument to target a field:

echo 'a-b-c d-e' | awk '{gsub(/-/,"_",$2); print}'
a-b-c d_e

Only the second column changed, the dashes in the first are still there. In the replacement text an & stands for the matched text, so sub(/o/,"[&]") turns tom into t[o]m. To get a real ampersand, write \\& inside the string.

One caveat: changing a field makes awk rebuild the line with the output separator, which is a single space by default. If your input is tab or comma separated, set -F and OFS together, or the columns come out joined by spaces.

Remember that the first argument is a regular expression, so an unescaped dot matches any character. In mawk, echo 'x.y' | awk '{gsub(/./,"-"); print}' prints ---, while gsub(/\./,"-") turns it into x-y. And with comma separated data, awk -F, -v OFS=, '{gsub(/-/,"_",$2); print}' turns a,b-c,d into a,b_c,d.

Further reading: GNU awk manual: string functions

More Awk tips 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}' echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}' All Awk tips (17) All topics

Link