[英]How to use regex in grep shell command
I am not able to use [-]+[\\n][-]+ this regex in shell. 我无法在外壳中使用[-] + [\\ n] [-] +此正则表达式。 Can somebody help to use it with escape characters in grep.
有人可以帮助将其与grep中的转义字符一起使用吗? I want to find lines like '----\\n----' from the file
我想从文件中查找类似于“ ---- \\ n ----”的行
Plain old grep
uses Basic Regular Expression so you don't have immediate access to the +
quantifier. 普通的旧
grep
使用基本正则表达式,因此您无法立即访问+
量词。 In modern (POSIX) grep
you can use this functionality, but it requires a backslash before the quantifier, like \\+
: 在现代(POSIX)
grep
您可以使用此功能,但是在量词前需要反斜杠,例如\\+
:
grep '-\+\\n-\+' file
(notice also the single quotes to prevent the shell from doing its own backslash substitution; and pay attention to how n
matches just itself and a literal backslash is matched either with a double \\\\
to escape it or in a character class [\\]
); (还请注意单引号,以防止外壳程序执行其自身的反斜杠替换;并注意
n
如何仅与自身匹配,而文字反斜杠与双\\\\
进行匹配以使其转义或在字符类[\\]
匹配) ; or you can use grep -E
(aka egrep
) which supports Extended Regular Expression : 或者您可以使用支持扩展正则表达式的
grep -E
(aka egrep
):
grep -E '-+\\n-+' file
For the record, [\\n]
matches a single character which can be either a literal backslash or a literal n
. 为了记录,
[\\n]
匹配一个字符,可以是文字反斜杠或文字n
。 This construct is called a character class; 这种构造称为字符类; inexplicably, newcomers seem to want to try to use square brackets for pretty much anything just because they "look like regex", apparently.
莫名其妙的是,新来者似乎想尝试将方括号用于几乎所有内容,仅仅是因为它们“看起来像正则表达式”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.