Re: How to change spaces in filenames

On 2006-08-11, larryalk wrote:
I would like to change all spaces in filename to dashes but can't
seem to get it working. The sed part works ok.

cd target_tree
for name in "`find . -maxdepth 99`"; do
mv "$name" "$name" | sed 's/\ /-/g'

The spaces in the filenames are one problem.

The sed part does not work. You need to put $name on sed's
standard input. You are executing it as a command, and not using
command substitution.

When testing the above with replacement echo statements, I get the
strange result that the the word "command_is" only occurs once at the
beginning of the $name list and the final sed command never appears at

echo "command_is "$name" `"$name" |sed '/\ /-/g'`"

I also tried with tr but cannot figure out how to make tr operate on
my $name variable - it seems to insist on a file.

No, tr does not need a file; it only reads the standard input

find . -depth -maxdepth 99 |
while IFS= read -r file
newname=$( printf "%s\n" "$filename" | tr ' ' '_' )
mv -i "$file" "$dirname/$newname"

If you are using bash or ksh93, you can use parameter expansion
instead of tr:

newname=${filename// /_}

Chris F.A. Johnson, author <>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence

Relevant Pages