Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading Each Line of an input file, performing grep on each line. 2

Status
Not open for further replies.
Jan 19, 2000
57
US
I have a file with thousands of lines consisting of serial numbers (1 serial per line, fixed length of six characters each).

I need to do a grep for each serial number on another file.

So, if the first three rows of my serial number file are:

A12345
B12345
C12345

Then the following grep operations need to be performed:

grep A12345 serialhistory.txt
grep B12345 serialhistory.txt
grep C12345 serialhistory.txt

How do i do this in a script?

Thanks!
 
Hi,

Code:
grep -f /path/to/serial.txt /path/to/another_file.txt
with serial.txt is your file containing serials
 
The -f option seems to depend on the flavour of grep (Solaris 8 vanilla doesn't have it for example). You could also:

while read name
do
grep name another_file.txt
done < serial.txt

I want to be good, is that not enough?
 
Apologies,

grep name another_file.txt should be

grep $name another_file.txt

I want to be good, is that not enough?
 
What does serialhistory.txt look like? If both files are sorted you may consider using comm, or even join. Let man be your friend.

Cheers,
ND [smile]
 
I second Ken's suggestion as a general 'how to do repeated actions using lines in a file' method. Just to add my twopenny worth, if the lines in the file have spaces then you may have trouble. This can be cured by settign IFS to newline i.e.
Code:
#Set IFS to newline
export IFS='
'

while read name
do
  action "$name" 
done < input file
or, in your case
Code:
export IFS='
'
while read name
do
  grep "$name" another_file.txt
done < serial.txt

Ceci n'est pas une signature
Columb Healy
 
Thank you all so much! I'm thrilled with the number and quality of the responses I received! The grep -f did the trick nicely. As it happened, there were no spaces on the lines, so the newline issue never surfaced.

Thanks again, folks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top