Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I want to learn more so I have tried to script more than just using the terminal. I know rename and I can rename image files with rename 's/ /_/g' *.jpg but when I write it in a shell script to point at a directory:

DIRECTORY="/foo/bar"

for imgfile in $(find $DIRECTORY -type f -name \*.jpg); do
    echo 'replacing whitespace in' $(basename $imgfile)
    rename -f 's/ /_/g' *.jpg 
done

it doesn't work and the terminal will take a file (example: 1234 abcd.jpg) and echo abcd.jpg. So where am I going wrong?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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 
   echo $i
done

You'll have

./file1 
1.jpg
./file2
2.jpg

because the shell breaks the argument at spaces. The output of the $(find ...) command will be

./file1 1.jpg 
./file2 2.jpg 

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"

otherwise *.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):

DIRECTORY="/foo/bar"
cd $DIRECTORY
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
done

added++: this link I found researching this answer is excellent.

share|improve this answer
    
no this still doesnt work. Im reading on how the script wont recognize two word and that is why I am only echo the first word. –  Matt Nov 19 '13 at 17:00
    
@Matt_2.0 --- I have further edited the answer. Happy bashing! –  Rmano Nov 19 '13 at 18:40
1  
+1 for Spaces in filenames are evil. –  Seth Nov 19 '13 at 23:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.