首页 > 解决方案 > Putty Search - String followed by one but not two symbols

问题描述

I am searching for a string in a path /home/folder/ that contains multiple .txt and .xls files. There exist instances where variable xyz is defined. An example would be: "xyz = if...else..."

There also exist instances where variable xyz is used as a condition. An example would be: ".... xyz==1 ..."

I want to find all instances where xyz is defined, not where xyz is used as a condition. I tried the following code and nothing worked...

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*\=[^=]'

I think my syntax is correct, but no results are returned. I tried using different shells but it made no difference. How would I search for a string in this case?

EDIT: I know instances of "xyz = ifelse" are present in files in the directory. These come up when I search using the following command:

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

标签: linuxshellunix

解决方案


Marktink的两个提示都是正确的:您需要添加-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

推荐阅读