如何逆匹配/黑名单用正则表达式?(How to inverse match/blacklist wi

2019-10-19 02:17发布

我已经看到了这个问题: 正则表达式匹配不包含字线?

但我不能得到它的工作。 我有一个shell脚本,我使用

string1.*string2.*string3

为了寻找3个字的文件,按照这个顺序。 但我想改变它,这样,如果badword5是在该文件中的那些话之间的任何地方,没有正则表达式匹配使用grep。

因此,这应该匹配:

./testing/test.txt:   let prep = "select string1, dog from cat",
          " where apple = 1",
          " and string2 = 2",
          " and grass = 8",
          " and string3 = ?"

但是,这不应该:

   ./testing/test.txt:   let prep = "select string1, dog from cat",
          " where apple = 1",
          " and string2 = 2",
          " and grass = 8",
          " and badword5 = 4", 
          " and string3 = ?"

我尝试过失败:

string1((?!badword5)|.)*string2((?!badword5)|.)*string3

整个脚本:

find . -name "$file_to_check" 2>/null | while read $FILE
do
   tr '\n' ' ' <"$FILE" | if grep -q "string1.*string2.*string3"; then echo "$FILE" ; fi
done >> $grep_out

Answer 1:

“为了寻找3个字的文件,按照这个顺序,但我想改变它,这样,如果badword5是在该文件中的那些话之间的任何地方,没有正则表达式匹配使用grep。”

事实上,和搜索模式延伸多条线路。
让我们放下grep的时刻和尝试不同的东西:

#!/bin/bash

find . -name "$file_to_check" 2>/dev/null | while read FILE
do
    SCORE=0
    tr ' ' '\n' <"$FILE" | while read WORD
    do
        case $WORD in
        "word1"    ) [ $SCORE = 0 ] && SCORE=1               ;;
        "word2"    ) [ $SCORE = 1 ] && SCORE=2               ;;
        "word3"    ) [ $SCORE = 2 ] && echo "$FILE" && break ;;
        "badword5" ) SCORE=0                                 ;;
        esac
    done        
done >grep_out

时线做以下的事情:

"    word1"      )    [ $SCORE     =       0 ] &&      SCORE  =       1  ;;
when word1 is found: and SCORE is equal to 0 then make SCORE equal to 1
when word2 is found: and SCORE is equal to 1 then make SCORE equal to 2
when word3 is found: and SCORE is equal to 2 then print filename and break out of the inner loop.


Answer 2:

您可以使用grep -v来跳过一行badword5

tr '\n' ' ' < "$FILE" | grep -v 'badword5' | if grep -q "string1.*string2.*string3"; then echo "$FILE" ; fi


文章来源: How to inverse match/blacklist with regex?
标签: regex shell unix