Answers
Q Renaming files
I’m trying to write a Bash script to get rid of Windows-illegal characters on my external drive and replace them with an underscore, since Windows implodes if it finds one.
Lauren Gordon
A There are several ways you can do this using regular expressions with perl or sed, but the simplest approach is probably to use tr, the translate command included with all distros. The program works by giving it two lists of characters, then it reads text from standard input and replaces any character that is in the first set with the corresponding character in the second set. You just need a list of the characters to replace. For example: will replace any occurrence of x, y or z with _. Normally both of the character lists would be the same length, but if the second list is shorter, the last character is reused for all the positions after it, so you can use a single character here if you would like everything to be replaced with the same character. A complete script could be:
The option for makes sure that you don’t inadvertently overwrite any files. You could end up with file names that contain sequences of underscores if they contain multiple instances of illegal characters. If you add (or ) to command it will replace multiple consecutive characters with a single underscore.
You’re reading a preview, subscribe to read more.
Start your free 30 days