Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am trying to rename all files in a folder replacing underscores with spaces.

i.e. this_is_a_test --> this is a test

but somehow I'm messing up the quoting

> for file in * ; do echo mv -v $file $(echo $file | sed 's/_/\\ /g') ; done
mv -v this_is_a_test this\ is\ a\ test

that looks OK, but if I remove the 'echo' mv complains as if the backslashes were removed

> for file in * ; do mv -v $file $(echo $file | sed 's/_/\\ /g') ; done
mv: target ‘test’ is not a directory

Can someone point out the error of my ways?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

There is a minor mistake. Use "$newfile" instead of only $newfile. You need to use "

Here is the correct one.

for file in * ; do mv -v "$file" "$(echo $file | sed 's/_/\\ /g')" ; done

If you have filename this_is_a_test it will rename file to this\ is\ a\ test.

In case if you want to rename the file to this is a test. Use the code below,

for file in * ; do mv -v "$file" "$(echo $file | sed 's/_/ /g')" ; done

It is a good practise to use variables inside "" while you writing good shell script.

share|improve this answer
Many thanks for the help, you solved the problem! –  ottotts Dec 14 '13 at 9:59

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.