question is: how to pass column position (eg, $2) dynamically through a loop.
Example file temp1
a 1 2
a 2 3
b 1 1
b 3 2
c 1 5
c 2 6
code so far (does not work:-))
#!/bin/bash
twopq () {
awk -v c1="$1" -v c2="$2" '{ if ($1==c1 && c2 == 1) {print}}' temp1 > temp2
}
twopq a $2
twopq b $3
Desired output in temp2 from 1st loop (1st col = 'a' and 2nd col = 1)
a 1 2
desired output in temp2 from 2nd loop (1st col= b and 3rd col = 1)
b 1 1
my pb is to pass the "$" through my loop to tell I'm looking for col2 in the first loop and col3 in the second loop
thanks for the help!
Like this:
#!/bin/bash
twopq () {
awk -v c1="$1" '($1==c1) {
for (i=2; i<=NF; i++)
if ($i == 1) {print;exit}
}' temp1 | tee -a temp2
}
twopq a 2
twopq b 3
a 1 2
b 1 1
Assumptions:
1
Adding a couple lines to demonstrate multiple matches:
$ cat temp1
a 1 2
a 2 3
b 1 1
b 3 2
c 1 5
c 2 6
d 1 5 # new line
d 1 9 # new line
A few tweaks to OP's current code:
twopq () { awk -v val="$1" -v colnum="$2" '$1==val && $(colnum)==1' temp1; }
Taking for a test drive:
$ twopq a 2
a 1 2
$ twopq b 3
b 1 1
$ twopq d 2
d 1 5
d 1 9
NOTES:
temp2
(eg, > temp2
to overwrite on each function call; >> temp2
to append with each function call)twopq a 2 > temp2
, twopq b 3 >> temp2
)did you tried to use $c2 inside if condition?
awk -v c1="$1" -v c2="$2" '{ if ($1==c1 && $c2 == 1) {print}}' temp1 > temp2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.