Sunday, October 08, 2006

handy way in shell of moving files with spaces in them

Say you have a bunch of files with spaces in the names, e.g.,:

02 Workinonit.m4a

And you want to move them to names without spaces (e.g., convert them to underscores). Luckily, there's an easy way: use 'read'

Let's say we want to copy them to filenames with an underscore replacing the space. To check that we have it right, the following command will echo what the result would be

find . -type f | while read f ; do echo cp "$f" "`echo "$f" | sed 's/ */_/g'`";done

cp ./18 Don't Cry.m4a ./18_Don't_Cry.m4a

Then just remove the first 'echo':

find . -type f | while read f ; do cp "$f" "`echo "$f" | sed 's/ /_/g'`";done

and you are done :) Interestingly, the site I found this on used sed 's/ */_g' (i.e., two spaces followed by an asterisk. This works, but I don't know why. I also found that you can use alternation to pick up other characters, like !,(). However, it seems sed has no way of dealing with apostrophes (according to all the man pages etc I consulted. Escaping it with a '\' will not work, nor will two backslashes. If you want to replace spaces, commas, exclamation marks and brackets in filenames, use:

sed -r 's/ |\(|\)|\,|\!/_/g'

I haven't yet worked out how to do all this in perl

No comments: