Spaces in filenames are evil.
I see three problems with the script.
1) when doing the
for... loop, you will have two different values when you find a file with space. i.e., if you have the files
"file1 1.jpg" and
"file2 2.jpg" and you do:
for i in $(find . -type f -name \*.jpg); do
because the shell breaks the argument at spaces. The output of the
$(find ...) command will be
Which are four words for the command
for to be assigned at
$i --- by default the shell treats spaces and newlines in the same way when expanding.
You can circumvent this changing the IFS char.
Your first line could look like:
IFS=$'\n' find $DIRECTORY -type f -name \*.jpg | while read -r imgfile; do
2) you are feeding the for loop with a single file name, so you should say:
rename -f 's/ /_/g' "$imgfile"
*.jpg is expanded in the current directory, and not in
$DIRECTORY (and note the quotes --- given that
$imgfile is going to have spaces in it).
3) even then, if
$DIRECTORY has some path component with spaces in it, the rename will fail (there will be intermediate directories that do not exist).
4) suggestion (keeping it simple):
rename -f 's/ /_/g' *.jpg
doesn't do what you want?
added: my script (created ages ago, when there was no
rename in Unix), is this --- it will remove spaces and tab in all files in current dir that have them in the name:
ls -1 | grep -E " |\t" | while read i; do
a=`echo $i | tr " \t" "__"`
mv -v "$i" $a
added++: this link I found researching this answer is excellent.