Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing bash variable to awk

Tags:

bash

awk

I'm trying to extract a row/column element from a text table using awk within a function in bash. Specifically:

getel() {
    awk -v col=$3 'FNR==$2 {print $col }' $1
}

The usage is:

getel <file> <row> <col>

If I type in:

awk -v col=2 'FNR==1 {print $col}' infile

at the bash prompt, I get row 1 col 2 as expected.
I dug through the various bash-awk questions but none seemed to get me to a solution.

Ultimately, I want to assign the result to another bash variable, ie:

FOUND=`awk -v col=2 'FNR==1 {print $col}' infile`

thanks

like image 819
bushidobrown Avatar asked Jan 24 '26 11:01

bushidobrown


1 Answers

Pass another command line variable to awk:

getel() {
    awk -v row=$2 -v col=$3 'NR==row {print $col }' $1
}
like image 188
anubhava Avatar answered Jan 26 '26 04:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!