2013-04-18 36 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