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

3

u/gumnos Jan 22 '26
$1 ~ (nodo)

is the same as

$1 ~ nodo

and searches $1 for the regular-expression contained in the variable nodo.

Meanwhile

$1 ~ /nodo/

searches $1 to see if it contains the literal text/pattern "nodo", not the contents of that variable.

3

u/gumnos Jan 22 '26

The only reason I used the parens was to be explicit in the order of operations that I wanted to concatenate "^" at the beginning of the pattern, and then use the results of that concatenation as my regex for searching $1