Bash-如何将非字母数字字符转换为“_”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6361337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash- How to convert non-alphanumerical character to "_"
提问by kheraud
I am trying to store user input in a variable and clean that variable in order to keep only alphanumerical caract + some others (I mean [a-zA-Z0-9-_]).
我试图将用户输入存储在一个变量中并清理该变量,以便仅保留字母数字字符 + 其他一些字符(我的意思是 [a-zA-Z0-9-_])。
I tried using this but it isn't exhaustive :
我尝试使用它,但它并不详尽:
SERVICE_NAME=$(echo $SERVICE_NAME | tr A-Z a-z | tr ' ' _ | tr \' _ | tr \" _)
Do you have some help for this?
你有什么帮助吗?
采纳答案by Steve Prentice
$ echo 'asd!@QCW@@D' | tr A-Z a-z | sed -e 's/[^a-zA-Z0-9\-]/_/g'
asd__qcw__d
I would use sedfor this and use the ^(not) operator in your set of valid characters and replace everything else with an underscore. The above shows the syntax with the output.
我会sed为此使用并^在您的一组有效字符中使用(not) 运算符,并用下划线替换其他所有内容。上面显示了输出的语法。
And, as a bonus, if you want to replace a run of invalid characters with one underscore, just add +to your regular expression (and use the -rswitch to sedto make it use extended regular expressions:
而且,作为奖励,如果您想用一个下划线替换一系列无效字符,只需添加+到您的正则表达式中(并使用-r开关sed使其使用扩展正则表达式:
$ echo 'asd!@QCW@@D' | tr A-Z a-z | sed -r 's/[^a-zA-Z0-9\-]+/_/g'
asd_qcw_d
回答by user unknown
Bash's string substitution is a fine thing: ${var//pat/rep}
Bash 的字符串替换是个好东西:${var//pat/rep}
val='Foo$%!*@BAR###baZ'
echo ${val//[^a-zA-Z_-]/_}
Foo_____BAR___baZ
A small explanation: The slash introduces a search/replace, a little like in sed (where it just delimits patterns). But you use a single slash for one replacement:
一个小解释:斜线引入了搜索/替换,有点像在 sed 中(它只是分隔模式)。但是您使用一个斜杠替换一个:
val='Foo$%!*@BAR###baZ'
echo ${val/[^a-zA-Z_-]/_}
Foo_%!*@BAR###baZ
Two slashes // mean replace all. Uncommon, but it has some logic, multiple slashes to mean multiple replace (please excuse my poor English).
两个斜线 // 表示全部替换。不常见,但它有一些逻辑,多个斜线表示多个替换(请原谅我的英语不好)。
And note how the $ is separated from the variable, but it is hard to modify a literal constant this way (which would be nice for testing). Modifying $1 isn't a no-brainer as well, afaik.
并注意 $ 是如何与变量分开的,但很难以这种方式修改文字常量(这对测试很有好处)。修改 1 美元也不是一件轻而易举的事,afaik。
回答by anubhava
I believe it can all be done in 1 single sed command like this:
我相信这一切都可以在 1 个 sed 命令中完成,如下所示:
echo 'Foo$%!*@BAR###baZ' | sed -e 's/[A-Z]/\L&/g' -e 's/[^a-z0-9\-]/_/g'
OUTPUT
输出
foo_____bar___baz
回答by jm666
perl way:
perl方式:
perl -ple 's/[^\w\-]/_/g'
pure bash way
纯粹的 bash 方式
a='foo-BAR_123,.:goo'
echo ${a//[^[:alnum:]-]/_}
produces:
产生:
foo-BAR_123___goo

