Have you ever inadvertently created multiple files containing “?”, “:” or “|” or any other file names with special chars? Imagine they are everywhere in the current path (in sub folders) within a given path and you want a quick way of renaming those files.
Well, after a bit of searching, reading and testing, I finally found an easy way to do it.
Let’s say you want to replace the “?” with an “_” in any file’s name in the current path (recursively). What would the command be?
Consider this - these are a bunch of files I deliberately created in this way:
./My ? File 2 ./My ? File 1 ./My Folder ./My Folder/My ? File
Then, I ran:
$ find . -name '*\?*' -exec bash -c 'echo mv $0 ${0/\?/_}' \"{}\" \;
Pay attention to the “\” char before the “?”. That’s the escape char.
Let’s see what happens when you run the command:
$ find . -name '*\?*' -exec bash -c 'echo mv $0 ${0/\?/_}' \"{}\" \; mv "./My ? File 2" "./My _ File 2" mv "./My ? File 1" "./My _ File 1" mv "./My Folder/My ? File" "./My Folder/My _ File"
Then just select the entire output of that command and copy paste it to your terminal:
$ mv "./My ? File 2" "./My _ File 2" $ mv "./My ? File 1" "./My _ File 1" $ mv "./My Folder/My ? File" "./My Folder/My _ File"
It works great. This can also be modified so that the entire procedure works with a single step like this:
$ (find . -name '*\?*' -exec bash -c 'echo mv $0 ${0/\?/_}' \"{}\" \;) | bash
Pretty cool isn’t it? 🙂