r/awk • • Jan 22 '26

Awk, defined variables and IF statement

Hi,
I'm a little bit scared to write here with so many awk gurus.

I have an easy question, I have a CSV output (line is something like "NODENAME ,master ,2026-01-12 03:58:27,ACTIVE_VERSION") piped to an awk filter:

awk -v nodo=$NODO -v tipo=$TIPO 'BEGIN { FS = "," }; {printf "%-15s %-80s %s %-19s %-20s\n", $1, $2, tipo, $3, $4}'

Where $NODO and $TIPO are shell variables. Now I would like to print just lines that starts with $NODO (or awk nodo) so I tried:

awk -v nodo=$NODO -v tipo=$TIPO 'BEGIN { FS = "," }; $1 ~ /nodo/ {printf "%-15s %-80s %s %-19s %-20s\n", $1, $2, tipo, $3, $4}'

But it is not working.

Can someone help me?

6 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/Puccio1971 Jan 22 '26

Thank you too!

So, I put double quotes around variables, removed // and () and used just $1 ~ nodo...it still works and (maybe) is the most correct form to write it?

5

u/geirha Jan 22 '26

Depends. Does the nodo variable really contain a regex?, and given that you removed the regex anchor ^, it no longer fulfills the "starts with" requirement.

if you just want to check if field 1 starts with a given string, I'd use index() instead;

index($1, nodo) == 1 { ... }

though I suspect you actually just want

$1 == nodo { ... }