extract a field from a long sentence!

Hi,

I want to extract the value of LENGTH column (high-lighted in red) from a file which will have several lines as shown below:

 
<INPUT VAR1 ="" DATATYPE ="number(p,s)" VAR2 ="" VAR3 ="3" VAR4="0" VAR5 ="ELEMITEM" VAR6 ="NO" VAR7 ="NOT A KEY" VAR8 ="17" LEVEL ="0" NAME ="UNIX" NULLABLE ="NOTNULL" OCCURS ="0" OFFSET ="19" LENGTH ="15" PHYSICALOFFSET ="29" PICTURETEXT ="" PRECISION ="15" SCALE ="0" USAGE_FLAGS =""/>
 

I am reading the file in while loop and want to do something like this

 
while read line
do
var_len=`echo $line | awk -F\" '/^ *=/{print $2}' RS=LENGTH`
done < $file

But it outputs as

-bash: syntax error near unexpected token `('

:confused:

Your help would be much appreciated.

-dips

If you just want the value you could use sed:

sed 's/.*LENGTH *="\([0-9]*\).*/\1/' file 

Move the left bracket if you want to include LENGTH =

This is working fine at my end. See below.

#cat $file
<INPUT VAR1 ="" DATATYPE ="number(p,s)" VAR2 ="" VAR3 ="3" VAR4="0" VAR5 ="ELEMITEM" VAR6 ="NO" VAR7 ="NOT A KEY" VAR8 ="17" LEVEL ="0" NAME ="UNIX" NULLABLE ="NOTNULL" OCCURS ="0" OFFSET ="19" LENGTH ="15" PHYSICALOFFSET ="29" PICTURETEXT ="" PRECISION ="15" SCALE ="0" USAGE_FLAGS =""/>
#while read line; do var_len=`echo $line | awk -F\" '/^ *=/{print $2}' RS=LENGTH`; echo $var_len;done < $file
15
#awk -F\" '/^ *=/{print $2}' RS=LENGTH  $file
15

Please post the remaining code if you have.

awk -F'[=" ]' '{for(x=y;x++<NF;){if($x=="LENGTH")print $(x+3)}}' file

Hi,

Thanks for the responses!

Linux xxxxxxxx 2.6.18-164.el5 #1 SMP Tue Aug 18 15:51:48 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux

May be it helps to resolve the mystery! :frowning:

-dips

---------- Post updated 2011-03-23 at 12:08 PM ---------- Previous update was 2011-03-22 at 06:06 PM ----------

Hi,

The problem got resolved. It was a very silly mistake! :o

while read line
do
var_len=`echo "$line" | awk -F\" '/^ *=/{print $2}' RS=LENGTH`
done < $file

I had to wrap the $line variable in double quotes to get it working.

-dips