Bash – awk + set variable inside the awk

awkbash

the following simple bash script print the row number ( from the file – list.txt )

function get_row

{ 

[[ $1 = 1 ]] &&  awk '{print $1}' list.txt
[[ $1 = 2 ]] &&  awk '{print $2}' list.txt

} 


get_row 1
get_row 2

but I want to wrote it more elegant…

is it possible to set "$1" as variable as awk '{print $val}'

so if I will call function as get_row 1 then $val will get the value 1

Best Answer

Do you want something like this?

function get_column
{ 
    awk -v val=$1 '{print $val}' list.txt
}

Above is returning the column match with $1 passing to the function. if you really need print the line match with line number in $1 from function, instead use below.

function get_row
{ 
    awk -v val=$1 'NR==val{print ; exit}' list.txt
}

Or let shell evaluated and set the val value and print that within awk as following:

function get_column
{ 
    awk '{print $val}' val=$1 list.txt
}
function get_row
{ 
    awk 'NR==val{print ; exit}' val=$1 list.txt
}

Here you are passing val with only numbers and if val was contain backslash escape character you will encounter a problem which awk does C escape sequence processing on values passed via -v val= and a shell variable with val="\\n" will change to value with \n by awk.

Related Question