简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM