Saturday, December 20, 2008

super cool way to move files with spaces in shell

I had a bunch of files named like;

IMG_2345 2.JPG

I wanted to remove the space and the 2 so that it would become like:

IMG_2345.JPG

How to do this in a one liner?

Can't use usual for file in `ls *\ 2.JPG`;do mv $file etc, as it will
treat the space as a newline (and quoting $file to "$file" won't do it
either.

There is a convenient way of doing this with 'read', as well as using built-in string replacement

ls *\ 2.JPG | while read line;do mv "$line" "${line/\ 2/}";done



Substring Replacement

${string/substring/replacement}

Replace first match of $substring with $replacement.
${string//substring/replacement}

Replace all matches of $substring with $replacement.

http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/string-manipulation.html

No comments: