rahul
rahul

Reputation: 6487

Shell Scripting: awk not printing local variables correctly

I am preparing data for a simple bigdata test. Below is my code.

#!/bin/bash
year_start=1900
year_end=2014
for(( year=$year_start; $year <= $year_end; year=`expr $year + 1` ))
do
    for(( d=1; $d < 365; d=`expr $d + 1` ))
    do
        random=$RANDOM
        echo $year|awk '{printf("%d%0.5d\n", $0,$random )}'
    done
done

However awk is printing the following instead of year+some random number

190001900
190001900
190001900
190001900
190001900
190001900
190001900
190001900

Any help?

Upvotes: 0

Views: 194

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

You cannot use shell variable as such in awk

use -v to pass the value to awk variable as

awk -v random=$random '{printf("%d%0.5d\n", $0,random )}'
  • -v random=$random creats an awk variable random and passes the sets it with the value of shell variable $random

Test

$ cat test
#!/bin/bash
year_start=1900
year_end=2014
for(( year=$year_start; $year <= $year_end; year=`expr $year + 1` ))
do
    for(( d=1; $d < 365; d=`expr $d + 1` ))
    do
        random=$RANDOM
        echo $year| awk -v random=$random '{printf("%d%0.5d\n", $0,random )}'

    done
done
$ bash test
190015628
190029371
190027290
190011319
190027379
190014108
190006841
190001113
190032492
190030980
190000745
190011316
190005771
190015510
190023285
190021061
190026820
^C

Upvotes: 1

Related Questions