user3799576 user3799576 - 9 months ago 50
Bash Question

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'`
egrep -v "^#" $FILE | awk '{print $2,$4,$5}' > $OUTPUT_FILE

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

Answer Source

The following test works for me:

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