Abdel
Abdel

Reputation: 6106

awk in while loop not working

I am trying the following command:

while read file
do
awk -v ID="$file" '$1==ID{print $0}' input2 > output
done < input1

input1 looks like this:

1
2
3
4

input2 looks like this:

2 a b c
3 a b c
5 a b c
6 a b c

The output should look like this:

3 a b c

So, in other words, if the first column of file input2 matches one of the values from file input1, I want the whole line from input2 printed to output. My while loop from above only produces empty files however... What could be the problem? Many thanks!

Upvotes: 0

Views: 660

Answers (2)

Ed Morton
Ed Morton

Reputation: 203169

Don't do that, it's immensely inefficient and fragile (see https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice). Do this instead:

awk 'NR==FNR{ids[$0];next} $1 in ids' input1 input2 > output

Upvotes: 3

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

Output is destroyed at each iteration Use >> instead of > or only last iteration shows

Upvotes: 2

Related Questions