Linux Shell中的“bash:意外的语法错误')”

Kon*_*Pak 2 command-line bash regex grep

我正在寻找引号内的字符串,其中 Linux 一词出现在位于引号内某处的括号之间。我必须使用正则表达式来做到这一点。我需要在 Linux 操作系统中执行此操作(使用 Virtual Box Terminal)。我使用了以下正则表达式:

 egrep "\"([^"]*)?\(([^"]*)?Linux([^"]*)?\)([^"]*)?\"" [FILE]
Run Code Online (Sandbox Code Playgroud)

但问题是,我明白了

bash: syntax error near unexpected token '("
Run Code Online (Sandbox Code Playgroud)

每次。可能是什么问题?我在“ http://regexr.com/ ”中尝试了这个正则表达式,它工作正常,正则表达式没有任何问题。但是 Linux shell 总是会产生同样的问题......我在括号前使用了“\”,因为它们是元字符。我在双引号前面做的同样的事情......但它不起作用。有人可以帮我吗?

Zan*_*nna 5

问题是表达式中未转义的双引号,例如围绕 this part "]*)?\(([^]"。如果你想传递文字",包括双引号或()[],那么你必须引用引号!你可以做

egrep "\"([^\"]*)?\(([^\"]*)?Linux([^\"]*)?\)([^\"]*)?\"" FILE
Run Code Online (Sandbox Code Playgroud)

但是一种不那么丑陋的方法是用单引号引用整个表达式,并且通常总是强(单)引用您的正则表达式,因此在将其作为参数传递给egrep或您正在使用的任何程序之前,shell 不会对它做任何奇怪的事情:

egrep '"([^"]*)?\(([^"]*)?Linux([^"]*)?\)([^"]*)?"' FILE
Run Code Online (Sandbox Code Playgroud)

(现在您也不需要转义外部的双引号,但您需要其他反斜杠来使括号成为文字(在 ERE 中))

如果您不想要该行的其余部分,也添加-o(仅匹配)

egrep -o '"([^"]*)?\(([^"]*)?Linux([^"]*)?\)([^"]*)?"' FILE
Run Code Online (Sandbox Code Playgroud)

你没有给出一个例子,所以我做了一个愚蠢的例子......这是以前的:

what
where is "the (lost Linux that I want) to find somewhere" in this file
and some junk
we don't want this thing "here where Linux is (not in brackets)"
Run Code Online (Sandbox Code Playgroud)

之后:

"the (lost Linux that I want) to find somewhere"
Run Code Online (Sandbox Code Playgroud)

(注意:grep您可以使用 GNUgrep -E而不是使用egrep