Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning printf output to a variable in awk command

Tags:

unix

I want to put leading 0 characters to some input, resulting in a fixed length (length given by a variable). The input can be a number or a string.
I want to catch the output in a variable.

I tried this:

awk '{j=$(printf "%04d\n"); echo $j}'  

but it is throwing this error:

awk: line 1: syntax error at or near printf
like image 764
king k Avatar asked Oct 31 '25 16:10

king k


1 Answers

Use

 awk '{j=sprintf("%04d", NR); print j}' 

to put the record number in the variable j.

like image 172
William Pursell Avatar answered Nov 04 '25 22:11

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!