如何使用ls创建正确的数组



我已经知道我可以使用array=( $( 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

我在整个脚本中有更多的for循环,具有sed和mv的各自指令,没有问题,但我对这部分代码有一个问题,似乎命令ls将整个结果保存在数组的第一个位置,即如果COS目录有cos1.txt, cos2.txt和cos3.txt,而不是将cos1.txt保存在${array[0]}中,cos2.txt保存在${array[1]}中,cos3.txt保存在${array[2]}中。

cos1.txtcos2.txtcos3.txt在${array[0]}中,位于数组第0位的整个列表。你知道怎么了吗?

不清楚您的实际问题是什么,但您应该这样编写代码:

# 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

最新更新