Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I need to run a command several times, each time with a new value:

grep VALUE0 myfile.txt
grep VALUE1 myfile.txt
grep VALUE2 myfile.txt

Because the grep command is "crafted" ad hoc (not always the same) and only the list of VALUEs is always the same I don't want to put the grep-command into a loop inside a bash-file. I would prefer to maintain my list of VALUEs in a seperate file like "values.txt" and let an ad-hoc shell command loop over this list of values read from "values.txt".

share|improve this question

3 Answers 3

up vote 2 down vote accepted

From the grep manual:

-f FILE, --file=FILE

Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.)

You could create a file with the patterns, one per line, and just run grep -f patternfile …. Perhaps it doesn't fit you, but it's difficult to know without explicit examples.

share|improve this answer
    
This is cool! I was looking more for the xargs way, but this one seems even better. Thanks! –  tschloss Apr 8 '13 at 15:09

You can do this using xargs:

xargs -a values.txt -I {} grep {} myfile.txt

This means that the file values.txt is read, one line at a time, then the command grep ... myfile.txt is run, where ... is being replaces with the content of the line read (I used {} because that's what find also uses.)

That being said, I can also tell you that with

egrep 'VALUE0|VALUE1|VALUE2' myfile.txt

you can search for more than one text at a time.

share|improve this answer
    
Cool, xargs seems to be exactly what I was looking for! The second idea is interesting as well. Thanks for both!! –  tschloss Apr 8 '13 at 15:06

Try this:

#!/bin/bash

while read value
do
    grep $value myfile.txt
done < values.txt

Keep the values in values.txt file, each in separate line.

share|improve this answer
    
Thanks. I did not want to put the grep statement inside the batch file, because it changes everytime. Thanks anyway. –  tschloss Apr 8 '13 at 15:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.