簡體   English   中英

Shell腳本中的嵌套For循環無法正確迭代數組

[英]Nested For Loop in Shell Script not correctly iterating over arrays

我正在嘗試使用嵌套的for循環來創建文件。 我有以下三個數組:

    a=( 1000 2000 3000 )
    b=( 10515 7515 4515 )
    c=( 10 20 30 40 )

使用這些數組將指定我的for循環將搜索哪些文件(目的是從先前存在的文件中復制數據並將其復制到新創建的文件中)。

    for tom in "${tom[@]}"
    do
       for dick in "${dick[@]}"
       do
          for harry in "${harry[@]}"
          do
             FILENAME="this_is_file_${tom}_${dick}_c0.out"
             NEWFILE="this_is_newfile_${tom}_${dick}_${harry}.out"
             cat $FILENAME >> $NEWFILE
             awk 'NR==n{$3=a}1' n="${x}" a="${harry}" $NEWFILE &> tmp && mv tmp $NEWFILE
             mv $NEWFILE NewFiles
             done
          done
       done
    done

(我已經定義了x =“ string”)。 到目前為止,當for循環執行一次迭代時,我的代碼生成所有文件,但是下一個循環返回到最后一個數組值4515開始並跳過第一個10515值。 我得到40個文件,這是正確的數目,但是當tom的數組的值是2000和3000時,dick的數組僅使用數組值7515和4515生成文件。它重復兩次值4515兩次,給出以下文件列表:

this_is_newfile_1000_10515_10.out
this_is_newfile_1000_10515_20.out
this_is_newfile_1000_10515_30.out
this_is_newfile_1000_10515_40.out
this_is_newfile_1000_7515_10.out
this_is_newfile_1000_7515_20.out
this_is_newfile_1000_7515_30.out
this_is_newfile_1000_7515_40.out
this_is_newfile_1000_4515_10.out
this_is_newfile_1000_4515_20.out
this_is_newfile_1000_4515_30.out
this_is_newfile_1000_4515_40.out

這是時髦的地方,請注意tom的數組值2000,dick的值保持4515,而不是循環回到10515。

this_is_newfile_2000_4515_10.out
this_is_newfile_2000_4515_20.out
this_is_newfile_2000_4515_30.out
this_is_newfile_2000_4515_40.out
this_is_newfile_2000_7515_10.out
this_is_newfile_2000_7515_20.out
this_is_newfile_2000_7515_30.out
this_is_newfile_2000_7515_40.out
this_is_newfile_2000_4515_10.out
this_is_newfile_2000_4515_20.out
this_is_newfile_2000_4515_30.out
this_is_newfile_2000_4515_40.out

(很長的列表,很抱歉,我想弄清楚發生了什么。)對於toms數組值3000重復此操作。有人可以幫忙嗎? 關於使用awk的行,我還有另一個問題,我將在另一個條目中發布。

弄清楚我的問題。 在For循環中,我將tom,dick和harry用作變量。 但是在定義它們時,數組是

tom=(values)
dick=(values)
harry=(values)

變量名稱與for循環中的“計數器”變量相同。

for tom in ${tom[@]}
do
   something
done

相反,它應該是這樣的:

for i in ${tom[@]}

應該使用i或其他不同於tom的變量。 這解決了問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM