Ubuntu – How to make the shell to recognize the file names returned by a `ls -A` command, and these names contain spaces

bashcommand linescripts

This is the part of the script I am using to rename the files returned by ls -A:

for FILE in `ls -A`
do
        ext=${FILE##*.}
        NUM=$(($NUM+1))
        NEWFILE=`echo $2_$NUM.$ext | sed 's/ /_/g'`

        mv "$FILE" "$NEWFILE"
done

But can not find names with space!
The $2 parameter can not be the cause of the error why I ever step a name without a space as a parameter, and this script takes that name and rename all files in the folder so to let them numbered and does not modify the file extension.
Unfortunately it does not rename files with spaces in the name.
Can someone help me?

Best Answer

ls -A for me writes multiple filenames on one line, separated by white space. If you tried adding -1 as in ls -A1 that would output one filename per line, and might work better for you.

I've run into the same problems with spaces in filename, espeically when using find, but separating names with a null character handles spaces & newlines in filenames:
find (...) -print0 | xargs -0 (do stuff here)

But, if you just want to rename files you might consider man rename it can do things like:

For example, to rename all files matching "*.bak" to strip the extension,
you might say
     rename 's/\.bak$//' *.bak
To translate uppercase names to lower, you'd use
     rename 'y/A-Z/a-z/' *

Or for a gui solution for a few directories Thunar has a nice Rename Multiple Files interface that can do numbering how you're describing too. I just tried some filenames with spaces combined with find to Thunar and it seems to work:
find . -type f -print0 | xargs -0 thunar -B