Bash – Replace Wildcard Character in Filenames

bashregexsearch-and-replace

I can't get this to work:

I have hundreds of files that our database developer has foolishly put asterisks in, so that we have files named like this:

*1*_Floorplan.jpg

I need to recursively (two levels in) search and replace all instances of "*" in all filenames and replace them with an underscore, "_".

I've tried the following but it fails, outputting the usage format for the "mv" command hundreds of times (as if for each file it would have tried to process), like I'd expect if I had invalid syntax, but I can't seem to find what's wrong with it:

for x in `find . -regex '.*/\*.*'` ; do mv $x `echo $x | sed s/\*/_/g` ; done

This is on a Mac (10.4) system, so it's a Darwin environment, if that makes any difference.

Please help!

Best Answer

Put quotes around $x everywhere it appears.

for x in `find . -regex '.*/\*.*'` ; do mv "$x" `echo "$x" | sed s/\*/_/g` ; done
Related Topic