且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从bash的字符串删除所有特殊字符和案例

更新时间:2022-10-17 23:36:56

 猫yourfile.txt | TR -dc'[:alnum:] \\ n \\ r'| TR[:上:]''[:降低:]'

第一个 TR 删除特殊字符。 D 表示删除 C 表示补码(反转字符集)。因此, -dc 表示删除除指定的所有字符。在 \\ n \\ r 被包括进来以preserve Linux或Windows风格的换行符,我假设你想

第二个转换大写字母为小写。

I am writing a bash script that I need to parse file names.

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?

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.