简体   繁体   中英

iterate through array values and assign to new variables shell

I have an input txt file with each line representing a value I need to capture and assign to a variable for processing. I have created an array as seen below, but I am wanting to create a loop using these variables to process the below (bottom) if statement for each line in the .txt. I tried the following, but it doesnt iterate through, it just assigns the same value for each line:

for i in ${pov[@]}
do
 echo ${pov[1]}
done

output:
$ ./sed
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16
SPT_SEQ_010,FY16

Here is the input and array I am using

##$cat seq_fy.txt
spt_seq_01,fy15
spt_seq_01,fy16
spt_seq_02,fy15
spt_seq_02,fy16

##array:
$ cat sed
pov=($(sed \n  seq_fy.txt))

##can echo pov:
$ cat sed
pov=($(sed \n  seq_fy.txt))
echo ${pov[1]}

$ ./sed
SPT_SEQ_010,FY16

I need to grab each pov value (${pov[1]} through [50]) and process as it does currently in an if statement/for loop as seen below, until the array is empty. An issue is there are other values determined by the pov#.

##current if statement being used and working after declaring each POV separately
##not using an array for the current process
if [ ! -z $pov01 ];
then
export step=${pov01//\"/}
export step03_01=$step
export pov=${pov01//\"/}
.... (using $pov as variable in connection string)
fi

You need to echo ${pov[i]} , not ${pov[1]} :

for i in ${pov[@]}
do
    echo ${pov[i]}
done

If I understand your code correctly, you can also read seq_fy.txt directly with a while loop:

cat seq_fy.txt | while read seqvar; do
    echo $seqvar
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM