Gerardo Mejía
Gerardo Mejía

Reputation: 1

Compare lines from two files and print just a column where it matches

I am new using AWK. I would thank you if you could help me.

I have two files

file1

1   2   3   4   ok  I
5   36  5   6   no  II
58  9   6   4   no  V
4   3   2   1   ok  III

file2

6   9   8   6
58  6   5   4
4   3   2   1
1   2   3   4

I want to find each row from file2 in file 1 and if it matches print columns 5 and 6 from file1

Output expected

ok III
ok I

Upvotes: 0

Views: 183

Answers (2)

Ed Morton
Ed Morton

Reputation: 204477

$ cat tst.awk
{ key = $1 FS $2 FS $3 FS $4 }
NR == FNR {
    map[key] = $5 OFS $6
    next
}
key in map { print map[key] }

.

$ awk -f tst.awk file1 file2
ok III
ok I

Upvotes: 1

Hai Vu
Hai Vu

Reputation: 40773

My solution is to create a file call match.awk:

FNR == NR {
    found[$1 "/" $2 "/" $3 "/" $4] = 1
}

FNR != NR && $1 "/" $2 "/" $3 "/" $4 in found {
    print $5, $6
}

Invoke it:

awk -f match.awk file2 file1

Discussion

  • Please note that in the command line above, we will go through file2 first. In the script, the processing of file2 is in the first block where FNR == NR
  • If we encounter lines in file2, we will create a key. For example, if the line contains 58 6 5 4, then the key will be 58/6/5/4. With this key, we mark the array found with a 1 (true)
  • The second block says, "We are seeing a line in file1 and this line has been found in file2. If that is the case, print out the result.

Upvotes: 1

Related Questions