awk loop and using shell in awk

Hi, everyone!

I have a file, when I print its $1 out it show several strings like this:

AABBCC
AEFJKLFG
FALEF
FAIWEHF

What I want to do is that, after output of each record, search the string in all files in the same folder, print out the record and file name.

This is what I want to get.

AABBCC  232  546   file1
AABBCC  432  653   file2
AABBCC  432  653   file3
AEFJKLFG  45   45   file1
AEFJKLFG  34   2     file3
.
.
.
.

try this..

while read x y
do
grep "$x" * | grep -v "^file" | awk -F ":" -v line="$x" '{print line,$2,$1}' >> output_file
done<file
1 Like

Cool! Thank you!

awk version:

awk 'NR==FNR{A[$1]; next} FILENAME!=ARGV[1] && $1 in A{print $0,FILENAME}' file * | sort -k1,1 -k4,4

--
@pamu: probably need to fix $x to avoid incomplete matches, for example:

grep "^[[:space:]]*$x[[:space:]]" 

and

grep -v "^file:"

also, the awk and the second grep could be placed outside the loop for efficiency...:

done < file | grep -v "^file:" | awk -F: '{print $2,$1}' > output_file

or

done < file | awk -F: '$1!="file"{print $2,$1}' > output_file

--
Neither of our solutions will work if there are too many files in the directory...

2 Likes

Wonderful! Thank you!