remove all spaces from all files in current folder

ls -1 | while read a; do mv "$a" `echo $a | sed -e 's/\ //g'`; done

2015-10-27 12:52:47

1 Alternatives + Submit Alt

What Others Think

@dfarre's perl rename is certainly the way to go, but if you want to use shell I'd make some changes. . First, I'd drop sed. The Unix way is to use the simplest tool you can. That'd be tr. echo $a | tr -d ' ' . You could also drop the echo and use a here-doc: tr -d ' ' <<< "$a" . Note: It's better to use $(command) rather than `command`. . But even that's still a bit heavy. bash can do the same using variable substitution: ${a// } (That's 'a' slash slash space . Next is the problem of files with no whitespace in them. mv fails! Ideally, you would quietly ignore such files. . Unfortunately, if you run "ls *\ *" and there aren't any matching files, it gives an error. You could redirect the error, but that's ugly ls *\ * 2> /dev/null . The alternative would be to use find find . -name '* *' . But... there's another problem with your command. If a filename ENDs in whitespace then that gets trimmed when the 'read' happens. To fix that you need to alter the IFS variable which tells bash how to separate things: find . -name '* *' | while IFS="" read A; do mv "$A" ${A// }; done . You might also want to add -v (verbose) to the mv command.
flatcap · 172 weeks and 3 days ago
Title is somewhat misleading, should be "remove all spaces from all file names in current folder"
jnxy · 170 weeks and 2 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: