mardi 30 novembre 2021

Awk if-statement to count the number of characters (wc -m) coming from a pipe

I tried to scratch my head around this issue and couldn't understand what it wrong about my one liner below.

Given that

echo "5" | wc -m 
2

and that

echo "55" | wc -m
3

I tried to add a zero in front of all numbers below 9 with an awk if-statement as follow:

echo "5" |  awk '{ if ( wc -m $0 -eq 2 ) print 0$1 ; else print $1 }'
05

which is correct, however with 2 digits numbers I get the same zero in front.

echo "55" |  awk '{ if ( wc -m $0 -eq 2 ) print 0$1 ; else print $1 }'
055

How come? It should return only 55 instead of 055. Am I constructing the if statement wrong?

I'm not interested in the optimal way to add leading zeros in the command line (there are enough duplicates of that), my question is regarding why the code above is not working.

Thanks!

Aucun commentaire:

Enregistrer un commentaire