Find all illegal Windows characters in a folder and subfolder

automatorcommand linefinderscript

I need an Automator script which finds all files with illegal Windows characters like <>:/\\|?* and replaces these characters with an underscore. The rest of the filename should remain unchanged.

As an alternative, I would use a terminal script. I know how to find them with find . -name "*[<>:/\\|?*]*", but I don't know how to change the names properly.

How do I do this?

Best Answer

I found a bash one-liner that finds each file and folder with invalid characters in the name and renames the file/folder, changing each invalid character to a dash:

find . -name "*[<>:\\|?*]*" -exec bash -c 'x="{}"; y=$(sed "s/[<>:\\|?*]\+/-/g" <<< "$x") && mv -n "$x" "$y" ' \;

It is possible that a file has an illegal name that would be corrected to the exact same legal name as another illegally named file (Example: two files named "fle"). The one-liner above will not change the name of the second (or further) illegally named file that would be corrected to the same name as the first. This means that you may still have some illegally named files after the one-liner runs. After you run this one-liner, run

find . -name "*[<>:\\|?*]*"

again to identify any illegally named files that still exist. One way to deal with this situation is to change the dash in the sed substitution to another character, e.g. underscore, and run the one-liner again.