Reputation: 61
I would very much appreciate if someone can help me.
I would like to perform this task using some commands, either grep, sed, or awk (or something else). I have two in-files.
File 1
0
1
4
File 2
S 0 1832 * 0 * * *
S 1 1801 * 0 * * *
H 1 1298 99.2 + 0 0 301M10I997M493I
S 2 1791 * 0 * * *
S 3 1720 * 0 * * *
S 4 1693 * 0 * * *
S 11 1693 * 0 * * *
The output what I want is
S 0 1832 * 0 * * *
S 1 1801 * 0 * * *
H 1 1298 99.2 + 0 0 301M10I997M493I
S 4 1693 * 0 * * *
So, if the second column of file2 matched with file1 lines, extract to the output. This is what I want to do.
Upvotes: 1
Views: 440
Reputation: 518
Here is the classic solution in awk:
awk 'FNR==NR{ a[$1]; next }$2 in a{ print $0 }' file1 file2
Output:
S 0 1832 * 0 * * *
S 1 1801 * 0 * * *
H 1 1298 99.2 + 0 0 301M10I997M493I
S 4 1693 * 0 * * *
The first part of the command is only executed on file1 due to the pattern FNR==NR which is only true for file1. It uses $1 as an index for the array a. The next command checks if $2 of file2 is in as an index in the array. $2 in file2 the desired match. And the last command prints the whole matching line of file2.
Upvotes: 2