Howto Pass A String as a parameter in AWK in Bash Script

I have a text file that I want to filter using awk. The text file is as follows:

foo 1 bar 2 bar 0.3 bar 100 qux 1033 

I want to filter these files using awk inside a bash script.

 #!/bin/bash #input file input=myfile.txt # I need to pass this as parameter # cos later I want to make it more general like # coltype=$1 col1type="foo" #Filters awk '$2>0 && $1==$col1type' $input 

But for some reason this did not work. What is the right way to do this?

+4
source share
4 answers

You need double quotes to allow variable interpolation, which means you need to avoid other dollar signs with backslashes so that $1 and $2 not interpolated. You also need double quotes around "$col1type" .

 awk "\$2>0 && \$1==\"$col1type\"" 
+4
source

pass it using the -v awk option. This way you highlight awk variables and shell variables. His lead is also without unnecessary quotes.

 #!/bin/bash #input file input=myfile.txt # I need to pass this as parameter # cos later I want to make it more general like # coltype=$1 col1type="foo" #Filters awk -vcoltype="$col1type" '$2>0 && $1==col1type' $input 
+10
source

double quotation mark

 awk '{print "'$1'"}' 


example:

 $./a.sh arg1 arg1 


 $cat a.sh echo "test" | awk '{print "'$1'"}' 


Linux testing

+5
source

Single quotes prevent variable expansion in bash:

 awk '$2>0 && $1=='"$col1type" 
+2
source

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


All Articles