Reputation: 3
I am trying to read a list of strings from one file and compare it with first column of second file and print the whole line.
I tried grep -f file1.txt file2.txt
but it compares the strings in the whole line and print it and I want to compare only with first column and print the line
Eg.
file1.txt
34534
67823
41400
file2.txt
41400 41440 52705 10254 20239 39975 40075 71022 82531
43897 41420 71104 10252 20243 41400 71065 83830
34534 41440 83203 10266 20255 40086 70262 84476
78314 22540 60000 10250 20247 40083 82432
67823 41440 70000 10246 20231 39646 40092 71052 83531
output is:
41400 41440 52705 10254 20239 39975 40075 71022 82531
43897 41420 71104 10252 20243 <b>41400</b> 71065 83830
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531
Below is Expected output:
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531
41400 41440 52705 10254 20239 39975 40075 71022 82531
Upvotes: 0
Views: 507
Reputation: 37404
I'd use awk:
$ awk 'NR==FNR{a[$0];next}($1 in a)' file1 file2
Output:
41400 41440 52705 10254 20239 39975 40075 71022 82531
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531
Explained:
$ awk ' # using awk
NR==FNR { # process the first file
a[$0] # hash words to a array
next # move to proces next word if any left
}
($1 in a) # if the first word of the second file record was hashed, output
' file1 file2
Update:
To print in the order of file1.txt
use:
$ awk '
NR==FNR {
a[$1]=a[$1] (a[$1]==""?"":RS) $0 # catenate records based on $1
next
}
{
print a[$0]
}' file2.txt <(tac file1.txt)
Above the order of records changing is demonstrated bu reversing the file1.txt
using rev
. Output in other order:
67823 41440 70000 10246 20231 39646 40092 71052 83531
34534 41440 83203 10266 20255 40086 70262 84476
41400 41440 52705 10254 20239 39975 40075 71022 82531
Upvotes: 2