Man Man - 1 month ago 8
Bash Question

shell script read file and search another file using awk

I am reading a file having numbers on each line.
I need to search another file meeting condition on those numbers and other conditions. I am trying to do this using awk. But facing problem.

file a.txt

1476

1477

1497

Now i need to print lines having these numbers at 12th column along with having 0 at 3rd column.

file b.txt

r 1.040496 2 1 ack 40 ------- 1 3.0 0.0 0 1165

r 1.040496 2 1 ack 40 ------- 1 3.0 0.0 0 1165

r 1.050528 2 1 ack 40 ------- 1 3.0 0.0 0 1165

r 1.050528 1 0 ack 40 ------- 1 3.0 0.0 0 1165

r 1.050528 1 0 ack 40 ------- 1 3.0 0.0 0 1476

r 1.06056 1 0 ack 40 ------- 1 3.0 0.0 0 1165

r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 1 1203

r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 1 1203

r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 2 1477

r 1.061392 0 1 tcp 1040 ------- 1 0.0 3.0 2 1204

r 1.071392 0 1 tcp 1040 ------- 1 0.0 3.0 1 1497

r 1.071392 1 2 tcp 1040 ------- 1 0.0 3.0 1 1203

my scipt
while read LINE
do
awk -F ' ' '($3 == 0) && ($12 == $LINE)' b.txt
done < a.txt

Returns nothing.

Answer

Try:

$ while read line; do awk -v x="$line" '($3 == 0) && ($12 == x)' b.txt; done < a.txt
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 2 1477
r 1.071392 0 1 tcp 1040 ------- 1 0.0 3.0 1 1497

Here, we use the -v option to assign awk variable x to have the value of shell variable $line.

Simplification

We don't need the shell loop:

$ awk 'FNR==NR{a[$1]; next} $3==0 && $12 in a' a.txt b.txt
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 2 1477
r 1.071392 0 1 tcp 1040 ------- 1 0.0 3.0 1 1497

While reading the first file, a.txt, we create a key is associative array a for the value on each line.

When reading the second file, b.txt, we print the line if $3==0 and field 12, $12, is a key in associative array a.

Comments