Computing.Net > Forums > Unix > variable in grep

Computing.Net: Over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to sign up now, it's free!

variable in grep

Reply to Message Icon

Original Message
Name: AccessHarry
Date: February 20, 2003 at 04:45:11 Pacific
Subject: variable in grep
OS: ?
CPU/Ram: ?
Comment:

I have a file with a list of 4 digit numbers. I would like to loop through the list, place the current number in a variable and then grep that number from another file. In the other file the number is held as "xxxx" in the part that I need to match it to. There are lots of other numbers on the same record in the second file hence the need for keeping the double quotes.

eg Number 4321
Grep '"4321"' myfile.001 >> newfile

Need it to be:

MyVar = 4321
Grep '"MyVar"' myfile.001 >> newfile

I know nothing in UNIX hence this relatively easy question!

Thanks in advance


Report Offensive Message For Removal


Response Number 1
Name: Frank
Date: February 20, 2003 at 04:57:01 Pacific
Reply: (edit)

Hi,

MyVar=4321
grep ${MyVar} myfile.001 >> newfile


Report Offensive Follow Up For Removal

Response Number 2
Name: AccessHarry
Date: February 20, 2003 at 05:32:13 Pacific
Reply: (edit)

Thanks Frank,

How do I keep the double quotes around the variable?

In the search file the records would be:

"01","001005006","5869","02084321254"
"01","001005008","4321","9123" etc

In the above example I want to return the second record because of "4321" rather than the first where it would be returned due to 4321 turning up in the last field. Hence why I need "4321" in the grep rather than 4321


Report Offensive Follow Up For Removal

Response Number 3
Name: WilliamRobertson
Date: February 20, 2003 at 05:36:30 Pacific
Reply: (edit)

Try:

while read teststring
do
grep \"${teststring}\" dummy.sh
done < master.lst


Report Offensive Follow Up For Removal

Response Number 4
Name: deeps
Date: February 20, 2003 at 05:43:34 Pacific
Reply: (edit)

If you are using k shell,

Try,

grep -w ${teststring} filename >>newfile

deeps


Report Offensive Follow Up For Removal

Response Number 5
Name: Frank
Date: February 20, 2003 at 23:59:34 Pacific
Reply: (edit)

Hi,
MyVar=4321
grep \"${MyVar}\" myfile.001 >> newfile

would also work.
What deeps suggested is ok but didn't work on HPUX. Because HP don't know the -w option.

Have fun
Frank


Report Offensive Follow Up For Removal







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home








Do you have your own blog?

Yes
No
I did before
I will soon


View Results

Poll Finishes In 2 Days.
Discuss in The Lounge
Poll History




Data Recovery Software