Operating System - HP-UX
1832973 Members
2470 Online
110048 Solutions
New Discussion

Match a field and print the line

 
Anand_30
Regular Advisor

Match a field and print the line

Hi,

I have a file with about 10000 lines. I have to match the 8th field of each line with a value (say "11") and output the line to another file if the field matches the value. Each field in the file is delimited with "|". I tried using

cat filename|awk -F "|" '{ if ($8 == 11 ) {getline; print $0}}

and also

cat filename | while read line
do
val=`cat -d"|" -f8 $line`
if [ $val -eq 11 ] ; then
echo $line
fi
done

Both did not work.

Can anyone please help me doing this.

Thanks,
Anand.
5 REPLIES 5
James A. Donovan
Honored Contributor

Re: Match a field and print the line

Does your second script really use "cat -d "|"
-f8 $line"? Or is that just a typo in your post?

You would want: val=`cut -d"|" -f8 $line`
Remember, wherever you go, there you are...
A. Clay Stephenson
Acclaimed Contributor

Re: Match a field and print the line

You are making this too hard:

awk -F '|' '{if ($8 == "11") print $0}' infilename > outfilename


If you want to evaluate $8 as an integer you need to coerce the type and change the comparison to
if (($8 + 0) == 11)
If it ain't broke, I can fix that.
Yan Wong
Frequent Advisor

Re: Match a field and print the line

try the following :
$cat test | awk -F "|" '$8 == 11 {print $0}'
or
val=$(cat -d "|" -f8 $line)

There are spaces in the field separators.
Yan Wong
Frequent Advisor

Re: Match a field and print the line

should be
cat filename |
Muthukumar_5
Honored Contributor

Re: Match a field and print the line

Yes. We can do with awk as,

awk -F "|" '{ if ( $8 == 11) print $0 }' >

Problem in your try is, you have matched one line's 8th element but print NEXT line there.

In next try,
try as,

while read line; do

val=`echo $line | cut -d"|" -f8`
if [ $val -eq 11 ] ; then
echo $line
fi

done <

HTH.
Easy to suggest when don't know about the problem!