2013-04-18 35 views
0

我已經知道我可以使用array=($(ls .))但我有這個代碼的下一個問題:如何用ls創建一個正確的數組?

array=($(ls ./COS/cos*.txt)) 
for (( i = 0 ; i <= ${#array[*]}-1; i++ )) 
do 
    sed 's/$'"/`echo \\\r`/" ${array[$i]} > ./COS/temp.txt 
    mv ./COS/temp.txt ${array[$i]} 
done 

我在整個腳本多爲循環用的SED相應的說明書和mv沒有問題型動物目錄,但是我有這部分代碼的問題,它看起來命令ls將整個結果保存在數組的第一個位置,即如果COS目錄有cos1.txt,cos2.txt和cos3.txt,而不是保存在$ {array [0]}中的cos1.txt,$ {array [1]}中的cos2.txt和$ {array [2]中的cos3.txt正在保存:

cos1.txt cos2.txt cos3.txt in $ {array [0]},整個列表位於數組的possition 0中。 你知道什麼是錯的嗎?

+0

你試圖用'sed'命令做什麼? – chepner

回答

1

目前還不清楚你的實際問題是什麼,但你應該寫這樣的代碼:

# Don't use ls. Just let the glob expand to the list of files 
array=(./COS/cos*.txt) 
# Don't iterate over array indices; just iterate over the items themselves 
for fname in "${array[@]}"; do 
do 
    # Are you trying to add a carriage return to the end of each line? 
    sed "s/\$/$'\r'/" "$fname" > ./COS/temp.txt 
    mv ./COS/temp.txt "$fname" 
done 

你甚至都不需要的陣列;你可以簡單地把glob放在for循環中:

for fname in ./COS/cos*.txt; do 
    ... 
done