Search code examples
arraysfor-loopls

How to create a correct array with ls?


I already know that I can use array=( $( ls . ) ) but I have the next problem with this code:

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

I have more for loops in the whole script with differents directories with the respective instructions of sed and mv with no problems, but I have a problem with this part of code, it appears the command ls is saving the entire result in the first possition of the array, i.e. if the COS directory has cos1.txt, cos2.txt and cos3.txt, instead of saving cos1.txt in ${array[0]}, cos2.txt in ${array[1]} and cos3.txt in ${array[2]} is saving:

cos1.txt cos2.txt cos3.txt in ${array[0]}, the entire list in the possition 0 of the array. Do you know what is wrong?


Solution

  • It's not clear what your actual problem is, but you should write the code like this:

    # 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
    

    You don't even need the array; you can simply put the glob in the for loop:

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