Re: Array variables getting lost





On 1/17/2008 2:50 PM, Brian Greaney wrote:
On Thu, 17 Jan 2008 14:23:03 -0600, Ed Morton wrote:



On 1/17/2008 1:24 PM, Brian Greaney wrote:

Once again I need help!
I have the following segment of a script:
# #! /bin/bash
# PVCs
p=0
cut -f 1 -d, BT_00|
while IFS=, read PVC #loop through 1st field
do
p=$((++p))
pvc[$p]=$PVC
echo $p ${pvc[$p]}
done

echo "<Cell ss:Index=\"2\" ss:StyleID=\"s136\"/>">>File1.xml
echo "<Cell ss:StyleID=\"s142\"><Data ss:Type=\"String\">$pvc[1]</Data></Cell>">>File1.xml
echo "<Cell ss:StyleID=\"s144\"><Data ss:Type=\"String\">$pvc[5]</Data></Cell>">>File1.xml
echo "<Cell ss:StyleID=\"s142\"><Data ss:Type=\"String\">${pvc[1]}</Data></Cell>">>File1.xml
echo "<Cell ss:StyleID=\"s144\"><Data
ss:Type=\"String\">${pvc[5]}</Data></Cell>">>File1.xml

For brevity I've left out some trivia, although this does actually execute
and gives the following:

1 CSAK205523
2 CSAK205547
3 CSAK205599
4 CSAK305545
5 CSAK309923
<Cell ss:Index="2" ss:StyleID="s136"/>
<Cell ss:StyleID="s142"><Data ss:Type="String">[1]</Data></Cell>
<Cell ss:StyleID="s144"><Data ss:Type="String">[5]</Data></Cell>
<Cell ss:StyleID="s142"><Data ss:Type="String"></Data></Cell>
<Cell ss:StyleID="s144"><Data ss:Type="String"></Data></Cell>

So in the 'loop' the correct variables are seen in the array (evidence
the CSAK.... )
But when I include them in the echo trying either $pvc[x] or ${pvc[x]} I
get either just the index or a null!

Where am I going wrong??

The loop is inside subshell courtesy of the pipe. See
http://www.unixguide.net/unix/bash/E4.shtml. Usually a loop is the wrong
approach to solve problems in shell.

In the above case, try this instead:

awk -F, '{
pvc[NR]=$1
print NR, pvc[NR]
}
END {
print "<Cell ss:Index=\"2\" ss:StyleID=\"s136\"/>"
printf "<Cell ss:StyleID=\"s142\"><Data ss:Type=\"String\">%s</Data></Cell>\n",
pvc[1]
print "<Cell ss:StyleID=\"s144\"><Data ss:Type=\"String\">%s</Data></Cell>\n",
pvc[5]
}' BT_00 >> File1.xml

Regards,

Ed.

Many thanks again I will try that (tomorrow)

Just change that last "print" to a "printf" before you do.

PS your last advice worked for me! Thanks


You're welcome.

Ed.

.



Relevant Pages