user2066431
user2066431

Reputation: 21

How to filter based on another file

Say I have a file in this format file 1:

kk a 1
rf c 3
df g 7
er e 4
es b 3

and another file 2:

c
g
e

I want filter the second column based on file 2 and output a file like this:

rf c 3
df g 7
er e 4

how would be the linux command for this?

Upvotes: 2

Views: 2739

Answers (3)

wudeng
wudeng

Reputation: 815

awk 'NR==FNR{A[$1];next}($2 in A)' file2 file1

Upvotes: 2

yankee
yankee

Reputation: 40850

Not necessarily fast or pretty, but does the trick:

cut -f 2 -d ' ' file1 | while read letter; do grep -n "$letter" file2 | cut -d ':' -f 1 | while read lineNo; do sed $((lineNo+1))'!d' file1; done; done;

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74098

You can use join for this, if both files are sorted or in the correct order. Although this gives a different output

join --nocheck-order -1 2 -2 1 file1.txt file2.txt

gives

c rf 3
g df 7
e er 4

With perl, you can read the keys file and then check each line for a match

use strict;
use warnings;

my %keys;
open(my $f1, '<', 'file2.txt') or die("Cannot open file2.txt: $!");
while (<$f1>) {
    chomp;
    $keys{$_} = 1;
}

close($f1);

open(my $f2, '<', 'file1.txt') or die("Cannot open file1.txt: $!");
while (<$f2>) {
    my(undef, $col2, undef) = split(' ', $_);
    print if ($keys{$col2});
}

close($f2);

This will give the desired

rf c 3
df g 7
er e 4

Upvotes: 0

Related Questions