bash GREP:正则表达式中的变量

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

GREP: variable in regular expression

regexbashgrep

提问by KeinReverb Leonardo Gabrielli

If I want to look whether a string is alphanumeric and shorter than a certain value, say 10, I would do like this (in BASH+GREP):

如果我想查看一个字符串是否是字母数字并且比某个值短,比如 10,我会这样做(在 BASH+GREP 中):

if grep '^[0-9a-zA-Z]\{1,10\}$' <<<$1 ; then ...

if grep '^[0-9a-zA-Z]\{1,10\}$' <<<$1 ; then ...

(BTW: I'm checking for $1, i.e. the first argument)

(顺便说一句:我正在检查 $1,即第一个参数)

What if I want the value 10 to be written on a variable, e.g.

如果我想将值 10 写在变量上怎么办,例如

UUID_LEN=10
if grep '^[0-9a-zA-Z]\{1,$UUID_LEN\}$' <<< ; then ...

I tried all sort of escapes, braces and so on, but could not avoid the error message

我尝试了各种转义、大括号等,但无法避免错误消息

grep: Invalid content of \{\}

After googling and reading bash and grep tutorials I'm pretty convinced it can't be done. Am I wrong? Any way to go around this?

在谷歌搜索和阅读 bash 和 grep 教程后,我非常确信这是不可能的。我错了吗?有什么办法可以解决这个问题吗?

采纳答案by chepner

You need to use double quotes so that the shell expands the parameter before passing the resulting argument to grep:

您需要使用双引号,以便 shell 在将结果参数传递给之前扩展参数grep

if grep "^[0-9a-zA-Z]\{1,$UUID_LEN\}$" <<< ; then ...

bashcan perform regular expression matching itself, without having to start another process to run grep:

bash可以自己执行正则表达式匹配,而不必启动另一个进程来运行grep

if [[  =~ ^[0-9a-zA-Z]{1,$UUID_LEN}$ ]]; then