[CLUE-Tech] removing spaces from filenames

David Anselmi anselmi at anselmi.us
Sat May 15 18:19:33 MDT 2004


Angelo Bertolli wrote:
> The for loop in bash treats the spaces in file names as different 
> "elements" for the loop.  This is really annoying as I want to process a 
> bunch of files with spaces in them.  Is there any way I can get around 
> this?  Putting " " around the names doesn't seem to help.

Um.  It isn't the for loop (necessarily), it's the command line built 
from the expansion of the loop variable.  (Caveat: this is bash on 
linux, ymmv.)  So, given a directory containing:

file 1
file 2

I do:

for file in * ; do
   touch $file.bak
done

I expect to see:

file 1
file 1.bak
file 2
file 2.bak

But I acutally get:

1.bak
2.bak
file
file 1
file 2

Well, think about it.  The commands I ran are:

touch file 1.bak
touch file 2.bak

and there you go.  The way to get the expected behavior is:

for file in * ; do
   touch "$file".bak
done

The quotes make $file expand into one word for the touch command. 
Single quotes won't work as they'll prevent the expansion of $file.

If you're doing something besides file globbing in the for line things 
might be different.  If you want to list files rather than use *, you 
have to quote their names on the for line and also quote the variable 
expansion.

If I haven't answered you well enough, ask again.  This is all explained 
in bash(1).  I'm sure if you look at it the answer will jump right out 
at you ;-)  (I have a printed copy of bash(1) that's 57 pages.  Then 
there's the reference manual at 132 and the FAQ isn't short either.)

HTH,
Dave



More information about the clue-tech mailing list