I'm trying to execute this bash script that loops over files (that have spaces in the name) in the current directory and creates a new folder with the first character of the file (if not already created) and moves that file to the folder. This is my code:
for i in `/bin/ls | xargs`
do
dir=`echo "$i" | cut -c 1 -`
mkdir -m777 -p "$dir"
mv "$i" "$dir"
done
The problem with this seems to be that it treats the each word in the file as a separate file, so although it creates the folder correctly , it can't move the file to that folder because the name of the file that it looks for is only the first word of the actual file. I looked at other answers to similar questions but this is the closest I've been able to get.
EDIT:
I replaced " for i in /bin/ls | xargs
" with " for i in * " as @steeldriver suggested, and although it fixed my original problem, I'm getting errors like these:
mv: cannot move '`' to a subdirectory of itself, '`/`'
mv: invalid option -- ' '
mv: missing destination file operand after '-'
mv: invalid option -- '.'
mv: invalid option -- ')'
mv: invalid option -- '+'
mv: cannot move ''$'\340' to a subdirectory of itself, ''$'\340''/'$'\340'
mv: cannot move ''$'\303' to a subdirectory of itself, ''$'\303''/'$'\303'
mv: cannot move ''$'\305' to a subdirectory of itself, ''$'\305''/'$'\305'
mv: invalid option -- '1'
I think some of these files may start with non-ascii characters (I can't view the contents because there are too many files). Is there a work around to handle these cases?
for i in *; do ...
- see Bash Pitfall #1 – steeldriver May 07 '19 at 21:48ls
. You should probably look into either usingfind
or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here. – DopeGhoti May 07 '19 at 21:55t
. – DopeGhoti May 07 '19 at 22:03