从bash的字符串删除所有特殊字符和案例 [英] Remove all special characters and case from string in bash

查看:117
本文介绍了从bash的字符串删除所有特殊字符和案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个bash脚本,我需要解析的文件名。

这将需要删除所有特殊字符(包括空格):并更改所有大写字母为小写像这样的事情!?-_:

Some_randoM数据1-A

更多数据0

somerandomdata1a

moredata0

我已经看到了很多的问题在许多不同的编程语言做到这一点,但不是在bash。有没有做到这一点的好办法?


解决方案

 猫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.

这篇关于从bash的字符串删除所有特殊字符和案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆