腻子搜索-字符串后跟一个但不是两个符号

时间:2019-02-05 20:14:26

标签: linux shell unix

我正在/ home / folder /路径中搜索一个包含多个.txt和.xls文件的字符串。在某些情况下,定义了变量xyz。一个例子是: “ xyz = if ... else ...”

也存在将变量xyz用作条件的情况。一个例子是: “ .... xyz == 1 ...”

我想查找所有定义了xyz的实例,而不是使用xyz作为条件的所有实例。我尝试了以下代码,但无济于事...

grep --include=\*.{txt,xls} -rnw '/home/folder/' -e 'xyz\s*\=(?!=)'
grep --include=\*.{txt,xls} -rnw '/home/folder/' -e 'xyz\s*\=(?!\=)'
grep --include=\*.{txt,xls} -rnw '/home/folder/' -e 'xyz\s*\=[^=]'

我认为我的语法正确,但是未返回任何结果。我尝试使用不同的外壳,但没有区别。在这种情况下,我将如何搜索字符串?

编辑:我知道目录中的文件中存在“ xyz = ifelse”的实例。当我使用以下命令搜索时会出现这些信息:

grep --include=\*.{txt,xls} -rnw '/home/folder/' -e 'xyz\s*\='

1 个答案:

答案 0 :(得分:1)

Mark tink 的两个提示都是正确的:您需要添加-P选项并使用以下方法摆脱-w改为\b

$ cat test.txt 
xyz = 14
xyz == 15
xyz=1
xyz==2
xyzz=4
zxyz=5

# No PCRE, no (correct) result
$ grep -e "xyz\s*\=(?!=)" test.txt 

# Missing instances without space between operator and value here
$ grep -P -w -e "xyz\s*\=(?!=)" test.txt 
xyz = 14

# Not checking for word boundary returns false positives
$ grep -P -e "xyz\s*\=(?!=)" test.txt 
xyz = 14
xyz=1
zxyz=5

# This is the result you want to see
$ grep -P -e "\bxyz\s*\=(?!=)" test.txt 
xyz = 14
xyz=1

# The same without PCRE
$ grep -e "\<xyz\s*\=[^=]" test.txt
xyz = 14
xyz=1
相关问题