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 Format1 min read
Ultimate Desktop Upgrade!
LXF316 will be on sale Tuesday 28th May 2024 Word processors that can help craft that novel you’ve always been talking about and organise large projects. Revive the old roleplaying system for a digital age as we recreate our own play-by-mail gaming
Linux Format3 min read
Original Prusa XL
The wait for a bigger 3D printer from Prusa Research has ended, and it certainly overdelivered. Instead of simply upsizing its classic i3 design, Prusa chose to create a completely new Core XY tool changer with a 360x360 mm build plate. The machine c
Linux Format5 min read
Some Ansible Advice For Around The Home!
Of late, this writer has been busy creating new virtual hosts for different things and decided that it would be an ideal time to get stuck into Ansible. Things have evolved in system management since Bash. Ansible is a great way to deploy software c

Related Books & Audiobooks