[CLUE-Tech] removing spaces from filenames?

marcus hall marcus at tuells.org
Mon Nov 18 22:22:04 MST 2002


On Sun, Nov 17, 2002 at 01:14:22PM -0700, Dave Price wrote:

> I have a _bunch_ of files that were created on a windoze system with
> embedded spaces in their names.  Can anyone recommend a technique to
> programmatically rename the files - replacing ' ' with '_' on both the
> file and dir names?
> 

Try a simple bash script, like this perhaps:

#!/bin/bash
find "$@" -name '* *' -depth | while read i
do	f=${i##*/} d=${i%$f} fx=${f// /_}
	echo mv "$d$f" "$d$fx"
done

This should work for all files (and directories) below the arguments
passed to the script.  Test it first with the "echo" in there to verify what
it would do, then remove the "echo" to actually do it.  This is short enough
to just type in directly, then use command history to edit it.

Things to watch out for are:

The calculation of the file and directory is subtle in that $d gets
any directory components *including* the trailing '/', or it is
'' if there is no directory.  Note that $f is set first to the basename,
then $d is set to the full name with the basename stripped off.

You need to be careful to only edit the bottom part of the path, since
the directories above cannot be changed with a simple mv command (i.e.
mv "a test dir/a test file" "a_test_dir/a_test_file" won't work.

Be careful about the order that the files/directories are processed.  The
-depth option to find searches the contents of each directory before the
directory itself.  Otherwise, the find might output something like:

a test dir
a test dir/a test file

That would produce the sequence of mvs:

mv "a test dir" "a_test_dir"
mv "a test dir/a test file" "a test dir/a_test_file"

instead of

mv "a test dir/a test file" "a test dir/a_test_file"
mv "a test dir" "a_test_dir"

See why the first would fail?  By the time the second mv runs, "a test dir"
no longer exists.

Now these comments are probably pretty long-winded for such a simple
script, but some of the considerations are probably important to think
about for other scripts as well...

marcus hall
marcus at tuells.org



More information about the clue-tech mailing list