5

consider file having values:

foo
boo
too

and another one:

foo,1
foo,2
boo,1 
soo,1

How to get only first match from the 2nd file, where output will be:

foo,1
boo,1
8

How about

$ awk -F, 'NR==FNR {a[$1]; next} $1 in a {print; delete a[$1]}' file1 file2
foo,1
boo,1 
6

A variation of the famous seen idiom.

awk -F, 'FNR==NR{a[$1]=1;next} a[$1]++==1' file1 file2

update

As @dave_thompson_085 pointed out, there might be multiple soo,# in the second file, it cause a[$1]++==1 to be true for the second one. He also gives several ways to fix it:

awk -F, 'FNR==NR{a[$1]=1;next} !--a[$1]' file1 file2
  • 2
    That will wrongly include soo,2 (if present). Going the other direction works: FNR==NR{a[$1]=1;next} a[$1]--==1 # or !--a[$1] – dave_thompson_085 May 23 at 23:57
  • @dave_thompson_085 Thanks for the heads up, updated. – dedowsdi May 24 at 0:33
2

Not actually awk, but it works. And I suppose it allows for easy extension.

#!/usr/bin/env bash

while IFS= read -r line; do
    grep -m1 "$line" "$2"
done < "$1"
$ ./script.sh file1 file2

Took the reading line-by-line from https://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable.
Then it's just 'find first match with content of line in file2'

  • 1
    Running grep multiple times in the body of a loop can be extremely slow. – Dennis Williamson May 24 at 14:07
2

I Have also used awk but with different method

command

awk -F "," 'NR==FNR{a[$1];next}($1 in a){print $0}' file1.txt file2.txt| awk -F "," '{if (!seen[$1]++)print }'

output

awk -F "," 'NR==FNR{a[$1];next}($1 in a){print $0}' file1.txt file2.txt| awk -F "," '{if (!seen[$1]++)print }'
foo,1
boo,1 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.