Linux Format

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.

More from Linux Format

Linux Format3 min read
Kernel Watch
Linus Torvalds announced the fourth RC (Release Candidate) for what will become Linux 6.9 in another few weeks. In his announcement, he noted that there was “Nothing particularly unusual going on this week – some new hardware mitigations may stand o
Linux Format2 min read
Specialist Tool Organisation
K ali works differently from the others as it has the security tools in the root of the app launcher. If you know what you’re looking for, the whole thing is searchable from the launcher. The ‘normal’ apps are located in the Usual Applications folder
Linux Format14 min read
Ubuntu at 20
Without Ubuntu, the current Linux landscape would be unrecognisable. Back in October 2004, the first 4.10 (2004.10) release of Ubuntu, with its intriguing Warty Warthog code name, leapt from obscurity to being one of the most downloaded Linux distrib

Related Books & Audiobooks