user3799576
user3799576

Reputation: 193

how to pass in a variable to awk commandline

I'm having some trouble passing bash script variables into awk command-line.

Here is pseudocode:

for FILE in $INPUT_DIR/*.txt; do
 filename=`echo $FILE | sed -n 's/^.*\(chr[0-9A-Z]*\).*.vcf$/\1/p'`
 OUTPUT_FILE=$OUTPUT_DIR/$filename.snps.txt
 egrep -v "^#" $FILE | awk '{print $2,$4,$5}' > $OUTPUT_FILE
done

The final line where I awk the columns, I would like it to be flexible or user input. For example, the user could want columns 6,7,and 8 as well, or column 133 and 138, or column 245 through 248. So how do I custom this so I can have that 'print $2 .... $5' be a user input thing? For example the user would run this script like : bash script.sh input_dir output_dir [user inputs whatever string of columns], and then I would get those columns in the output. I tried passing it in, but I guess I'm not getting the syntax right.

Upvotes: 10

Views: 14074

Answers (2)

aherrero
aherrero

Reputation: 333

With awk, you should declare the variable before use it. This is better than the escape method (awk '{print $'$var'}'):

awk -v var1="$col1" -v var2="$col2" 'BEGIN {print var1,var2 }'

Where $col1 and $col2 would be the input variables. Maybe you can try an input variable as string with "$2,$4,$5" and print this variable to get the values (I am not sure if this works)

Upvotes: 22

Michal Krzyz
Michal Krzyz

Reputation: 1636

The following test works for me:

A="\$3" ; ls -l | awk "{ print $A }"

Upvotes: -3

Related Questions