簡體   English   中英

grep中的正則表達式包含A,B,C ......但不包含Z的文件

[英]Regex in grep for files containing A,B,C… but not Z

花了幾個小時試圖用這個問題的部分答案自己回答這個問題; 所以我很抱歉,如果這已經得到了回答,但結合我能找到的部分解決方案來正確執行此搜索似乎超出了我的范圍。

我正在嘗試做的事情:在目錄中搜索包含多個唯一字符串的文件,文件中的任何位置,但不包含文件中任何位置的其他特定字符串。

這是我到目前為止的搜索:

pcregrep -riM '^(?=.*uniquestringA)(?=.*uniquestringB)(?=.*uniquestringC)(?=.*uniquestringD)(?=.*uniquestringE).*$' . 
| xargs grep -Li 'uniquestringZ'

我意識到這是可怕的,可怕的錯誤,因為我甚至似乎無法讓多行搜索工作而忽略字符串出現的順序。

任何幫助是極大的贊賞。

如果你的grep有前瞻,你應該可以做到

^(?!.*Z)(?=.*A)(?=.*B)(?=.*C)(.*)$

看得出來了

有了這個文件:

$ cat /tmp/grep_tgt.txt
A,B,C      # should match
A,B,C,D    # should match
A,C,D      # no match, lacking upper b
A,B,C,Z    # no match, has upper z

你可以使用perl one liner:

$ perl -ne 'print if /^(?!.*Z)(?=.*A)(?=.*B)(?=.*C)(.*)$/' /tmp/grep_tgt.txt
A,B,C      # should match
A,B,C,D    # should match

使用文件名:

$ find . -type f
./.DS_Store
./A-B-C
./A-B-C-Z
./A-C-D
./sub/A-B-C-D

您可以使用perl過濾文件名:

$ find . -type f | perl -ne 'print if /^(?!.*Z)(?=.*A)(?=.*B)(?=.*C)(.*)$/'
./A-B-C
./sub/A-B-C-D

如果要讀取文件內容以測試模式(如grep),可以執行以下操作:

$ find . -type f | xargs perl -ne 'print "$ARGV: $&\n" if /^
(?!.*Z)(?=.*A)(?=.*B)(?=.*C)(.*)$/'
./1.txt: A B C     # should match
./2.txt: A,B,C,D    # should match

我把四個文件放在一個目錄(1.txt .. 4.txt)中,文本里面的1.txt和2.txt匹配。

雖然它需要大量的grep調用,但您可以使用findgrep以簡單且符合POSIX的方式編寫它:

find . -type f \
  -exec grep -q "stringA" {} \; \
  -exec grep -q "stringB" {} \; \
  -exec grep -q "stringC" {} \; \
  -exec grep -q "stringD" {} \; \
  ! -exec grep -q "stringZ" {} \; \
  -print  # or whatever to do with matches

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM