bash 从 shell 脚本中的字符串中过滤出非字母字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17167385/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:43:13  来源:igfitidea点击:

Filter non-alphabetic characters out of string in shell script

regexbashshellscripting

提问by Rich

Very simple question but can't seem to find a simple answer...

很简单的问题,但似乎找不到简单的答案...

I am writing a bash script which needs to remove all non-alphabetic and non-numeric characters. Eg. I want...

我正在编写一个需要删除所有非字母和非数字字符的 bash 脚本。例如。我想要...

INPUT_STRING="ABC# .1-2-3"

OUTPUT_STRING= # some form of processing on $INPUT_STRING #

echo $OUTPUT_STRING
ABC123

I realize that this would be best solved using regex, but not sure how to use this effectively in the script.

我意识到使用正则表达式最好解决这个问题,但不确定如何在脚本中有效地使用它。

All help greatly appreciated...

非常感谢所有帮助...

回答by fedorqui 'SO stop harming'

You can use sedto strip all chars that are not a-z, A-Zor 0-9:

您可以使用sed删除所有不是a-z,A-Z或 的字符0-9

$ echo "ABC# .1-2-3" | sed 's/[^a-zA-Z0-9]//g'
ABC123

So in your case,

所以在你的情况下,

$ INPUT_STRING="ABC# .1-2-3"
$ OUTPUT_STRING=$(echo $INPUT_STRING | sed 's/[^a-zA-Z0-9]//g')
$ echo $OUTPUT_STRING
ABC123

回答by Dimitre Radoulov

$ INPUT_STRING="ABC# .1-2-3"
$ printf '%s\n' "${INPUT_STRING//[![:alnum:]]}"
ABC123