Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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 blackI would like to grep for the string 'black' in field 1 ONLY. So my expected output should be:
black goodyear tire
black michelin tireWhen 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!!

WANDr:
Here's an awk script matching on just field 1:
#!/bin/ksh
nawk ' {
if(match($1, "black"))
print $0
} ' data.fileI'm on Solaris and I need to use nawk. You may have to change that to awk.
Regards,
Nails

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

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
fiI 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

![]() |
reg Doskey in solaris
|
Can I start from beginnin...
|

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