reintakura
reintakura

Reputation: 33

grep not showing result which read id from file

I've two files named db_name.txt and id.txt

db_name.txt files :

111111  Steven
222222  Bob
333333  Marry
444444  July
555555  Venus
666666  Porter
777777  Guerson
888888  Yeti
999999  Piza

https://filedn.com/lErjiEcIItPyfm4zDdHlyIz/db_name.txt

id.txt files :

222222
444444
777777

https://filedn.com/lErjiEcIItPyfm4zDdHlyIz/id.txt

I want result like :

222222 Bob
444444 July
777777 Guerson

I already create shell script to loop id.txt content & cat db_name.txt with grep variable id for each line

#!/bin/bash

while IFS= read -r line
do
    cat db_name.txt | grep "$line"
done < "id.txt"

But there's no result

Upvotes: 3

Views: 729

Answers (2)

John1024
John1024

Reputation: 113924

Try:

$ grep -Ff id.txt db_name.txt
222222  Bob
444444  July
777777  Guerson

How it works:

  • -F tells grep to treat the patterns as fixed text (no active-regex characters).

  • -f id.txt tells grep to read the patterns in from file id.txt. Each line in id.txt is treated as a pattern, separate and independent of other lines. Output is produced if any one of the patterns matches.

Quick fix for DOS line-endings

id.dos is like id.txt but has DOS/Windows line endings. Because of that grep -Ff id.dos db_name.txt will produce no output. As a quick fix, try:

$ grep -Ff <(tr -d '\r' <id.dos) db_name.txt
222222  Bob
444444  July
777777  Guerson

Upvotes: 3

Jack Hammer
Jack Hammer

Reputation: 41

I ran your shell script and it works for me, so there may be a compatibility issue or other malfunction you are experiencing - but I have a better suggestion, since it looks like you want something like a database table join, you can avoid coding this altogether and just use that command. It's a basement favorite of mine:

join id.txt db.txt 
222222 Bob
444444 July
777777 Guerson

Note that your expected output is 'July' for 444444, not 'Marry' :-)

Join can be very useful, but you will need to be careful of that your input files are always sorted first by the 'sort' command, but yours is already sorted so I won't go into that.

I hope that helps.

Upvotes: 0

Related Questions