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 substr() cuts a piece out of a line, like a date from a number

Awk
~/tips/tip-awk-substr-cut-text

echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}'

Extracts part of a string by start position and length, counting from 1.

Fixed-width values are everywhere: dates like 20261201, IDs, timestamps glued together. When there is no separator to split on, substr takes a piece by position.

echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}'
2026-12-01

substr(string, start, length) counts from 1, not 0. Leave out the length and you get everything from the start position to the end of the string:

echo ABC | awk '{print substr($0,2)}'
BC

It combines well with toupper and tolower. To capitalise the first word: toupper(substr($1,1,1)) substr($1,2), which turns dies into Dies.

The caveat is the start position. Starting at 0 or below is not the same everywhere. In mawk, substr($0,0,2) on abc prints ab, while other awks treat the range differently and give a. Start at 1 and the question never comes up.

To take the last characters, combine it with length. In mawk, echo hello | awk '{print substr($0,length($0)-1)}' prints lo. A length that runs past the end is fine too: substr($0,2,100) on hello prints ello, so you do not have to count exactly.

The same idea works on a column: substr($3,1,10) cuts a timestamp down to its date part, and the rest of the line stays as it was.

Further reading: GNU awk manual: string functions

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 '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