Results 1 to 8 of 8
I'm trying to figure out how to find multiple variables within a file.
Example:::>
I have a script call finditem
[]more finditem
grep -i $1 /home/ItemList
[]more ItemList
Brown horse ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 09-16-2009 #1Just Joined!
- Join Date
- Sep 2009
- Posts
- 5
grep multiple variables in a file
I'm trying to figure out how to find multiple variables within a file.
Example:::>
I have a script call finditem
[]more finditem
grep -i $1 /home/ItemList
[]more ItemList
Brown horse 12
Black cat 34
Red fox 56
blue moon 78
yellow sun 90
#I want to grep for red and sun at the same time.
#any idea? (please)
- 09-16-2009 #2Code:
egrep -i '(red|sun)' ItemList Red fox 56 yellow sun 90
- 09-16-2009 #3Just Joined!
- Join Date
- Sep 2009
- Posts
- 5
how about if i need to grep for other things?
The idea i had behind it, was to run the script with the variables i need behind it.
[]finditem red sun
Red fox 56
yellow sun 90
or
[]finditem black 78
Black cat 34
blue moon 78
#I was starting off with 2 variables, but will need to increase the number of variables i'm searching for.
#Any other ideas?
- 09-16-2009 #4Just Joined!
- Join Date
- Sep 2009
- Posts
- 5
work around
i have a work around in place, but it's ugly as hell.
I have a script call finditem
[]more finditem
grep -i $1 /home/ItemList
grep -i $2 /home/ItemList
#if anyone has an idea on how to combind these two together; that would be awsome.
- 09-16-2009 #5
No offence, but why try and reinvent the wheel?

The mentioned egrep with the OR operator is perfectly capable of doing
any number of searches for your use case.
And the syntax is not that hard.
If you insist not to type the '(Var1|Var2|Var3)' every time,
one could count the number of varibles give to "finditem"
and then construct the egrep line according to that.
Calling grep multiple times like in your last example is just a waste of ressources
- 09-16-2009 #6Just Joined!
- Join Date
- Sep 2009
- Posts
- 5
alright, i halfway figured out my problem. My script wasn't liking the signle ticks. I have replaced them with double ticks.
Thanks for the help Irithori
- 09-16-2009 #7Just Joined!
- Join Date
- Sep 2009
- Posts
- 5
With the previous script;
I need to modify it so i can pull 1 item from the list or more as needed.
any suggestions?
- 09-16-2009 #8Linux Guru
- Join Date
- Nov 2007
- Location
- Córdoba (Spain)
- Posts
- 1,513
I am not 100% sure I understand you, but, if what you want is to run something like this:
You could consider using a loop and the shift command. shift -well- shifts the parameter list to the left, so $1 dissapears, and $2 becomes $1, and so on. So, you could do something like:Code:./finditem item1 item2 ... itemN
You could also use for, like in "for i in $@; done grep "$i" file; done".Code:while [ -n "$1" ]; do # as long as "$1" is not empty grep "$1" /whatever/file shift # shifts the argument list done


Reply With Quote
