Computing.Net > Forums > Unix > Using the grep command

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Click here to start participating now! Also, check out the New User Guide.

Using the grep command

Reply to Message Icon

Name: WANDr
Date: April 4, 2003 at 07:19:33 Pacific
OS: MDK
CPU/Ram: AMD
Comment:

Using the KORN SHELL ONLY, is there any way that I can grep for a string in column/field 1 only? For instance in a data file named inventory, i have:

black goodyear tire
black michelin tire
film window black

I would like to grep for the string 'black' in field 1 ONLY. So my expected output should be:

black goodyear tire
black michelin tire

When i tried using grep, it returned all three fields because they all contain the string black.

Also, is there a similar awk command that would do the same thing? Thanks in advance for your help!!



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: April 4, 2003 at 12:09:31 Pacific
Reply:

WANDr:

Here's an awk script matching on just field 1:

#!/bin/ksh

nawk ' {
if(match($1, "black"))
print $0
} ' data.file

I'm on Solaris and I need to use nawk. You may have to change that to awk.

Regards,

Nails



0

Response Number 2
Name: WANDr
Date: April 4, 2003 at 14:34:54 Pacific
Reply:

Nails,

Thank you very much! Do you know of a korn shell script that will do the same thing...possibly using grep?


0

Response Number 3
Name: nails
Date: April 4, 2003 at 15:27:44 Pacific
Reply:

WANDr:

You might try this out. I read each line and break it into 3 fields; echo the first field, and pipe it to grep black. If there's a match, the exit code is set to zero which is true, and the "and" echo's the 3 fields.

If you don't like the boolean expression, you can do this within the while loop:

echo $f1|grep black > /dev/null
if [ $? -eq 0 ]
then
echo $f1 $f2 $f3
fi

I would expect for a large amount of data, the awk script is more efficient.

Look out for the less than sign being dropped at the end of the while loop.


#!/bin/ksh

# break line into 3 fields
while read f1 f2 f3
do
{ echo $f1|grep black > /dev/null ; } && echo $f1 $f2 $f3
done data.file
# need a less than sign between "done" and "data.file"


Regards,

Nails


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


reg Doskey in solaris Can I start from beginnin...



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


Sponsored links

Ads by Google


Results for: Using the grep command

grep command www.computing.net/answers/unix/grep-command/6034.html

Help on grep command www.computing.net/answers/unix/help-on-grep-command/7376.html

using the sed command www.computing.net/answers/unix/using-the-sed-command/5791.html