$colnumber']++; } END { for (i in filetime) { ...">

How to pass bash parameter in awk script?

I have an awk file:

#!/bin/awk -f BEGIN { } { filetime[$'$colnumber']++; } END { for (i in filetime) { print filetime[i],i; } } 

And bash script:

 #!/bin/bash var1=$1 awk -f myawk.awk 

When I run:

 ls -la | ./countPar.sh 5 

I get an error message:

 ls -la | ./countPar.sh 5 awk: myawk.awk:6: filetime[$'$colnumber']++; awk: myawk.awk:6: ^ invalid char ''' in expression 

Why? $ colnumber needs to be replaced with 5, so awk should read the 5th column of ls ouput. Thanks.

+4
source share
3 answers

You can pass variables to your awk script directly from the command line.

Change this line:

 filetime[$'$colnumber']++; 

To:

 filetime[colnumber]++; 

And run:

 ls -al | awk -f ./myawk.awk -v colnumber=5 

If you really want to use a bash wrapper:

 #!/bin/bash var1=$1 awk -f myawk.awk colnumber=$var1 

(with the same change to the script as above.)

If you want to use environment variables, use:

 #!/bin/bash export var1=$1 awk -f myawk.awk 

and

 filetime[ENVIRON["var1"]]++; 

(I really don't understand what the purpose of your awk script is. The last part can be simplified:

 END { print filetime[colnumber],colnumber; } 

and parsing ls output is usually a bad idea.)

+5
source

The easiest way to do this:

 #!/bin/bash var=$1 awk -v colnumber="${var}" -f /your/script 

But in your awk script you don't need $ before colnumber.

NTN

+2
source

Passing 3 variables to the script myscript.sh var1 - the number of the column on which the condition is set. Although var2 and var3 are input and temporary files.

 #!/bin/ksh var1=$1 var2=$2 var3=$3 awk -v col="${var1}" -f awkscript.awk ${var2} > $var3 mv ${var3} ${var2} 

execute it as below -

 ./myscript.sh 2 file.txt temp.txt 
0
source

Source: https://habr.com/ru/post/1387027/


All Articles