Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass in a variable to awk commandline

Tags:

bash

shell

awk

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.

like image 280
user3799576 Avatar asked Oct 21 '16 13:10

user3799576


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 + ...

How do you pass a variable in Linux?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

How run awk from command line?

In order to tell awk to use that file for its program, you type: awk -f source-file input-file1 input-file2 … The -f instructs the awk utility to get the awk program from the file source-file (see Command-Line Options). Any filename can be used for source-file .


1 Answers

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)

like image 101
aherrero Avatar answered Oct 02 '22 14:10

aherrero