Remove all special characters and case from string in bash

bash, linux, parsing, regex, shell

Solution

cat yourfile.txt | tr -dc '[:alnum:]\n\r' | tr '[:upper:]' '[:lower:]'

The first `tr` deletes special characters. `d` means delete, `c` means complement (invert the character set). So, `-dc` means delete all characters except those specified. The `\n` and `\r` are included to preserve linux or windows style newlines, which I assume you want.

The second one translates uppercase characters to lowercase.

Problem

I am writing a bash script that needs to parse filenames. It will need to remove all special characters (including space): "!?.-_ and change all uppercase letters to lowercase. Something like this: ``` Some_randoM data1-A More Data0 ``` to: ``` somerandomdata1a moredata0 ``` I have seen lots of questions to do this in many different programming languages, but not in bash. Is there a good way to do this?

Original source

Related problems