Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables into awk from bash

I am writing a shell script file in which I have to print certain columns of a file. So I try to use awk. The column numbers are calculated in the script. Nprop is a variable in a for loop, that changes from 1 to 8.

avg=1+3*$nprop
awk -v a=$avg '{print $a " " $a+1 " " $a+2}' $filename5 >> neig5.dat

I have tried the following also:

awk -v a=$avg '{print $a " " $(a+1) " " $(a+2) }' $filename5 >> neig5.dat

This results in printing the first three columns all the time.

like image 746
sodiumnitrate Avatar asked May 02 '13 14:05

sodiumnitrate


People also ask

How do you use global variables in awk?

All variables in AWK are global, except when we make variables local to function. To make a variable local to a function, we simply declare the variable as an argument after the other function arguments. The output of the execution of the previous code is as follows: p + ...

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

avg=1+3*$nprop

This will set $avg to 1+3*4, literally, if $prop is 4 for instance. You should be evaluating that expression:

avg=$(( 1+3*$nprop ))

And use the version of the awk script with parenthesis.

like image 177
Mat Avatar answered Oct 07 '22 18:10

Mat