String 在具有新行的文本之间搜索包含两个或多个特定单词的文件

String 在具有新行的文本之间搜索包含两个或多个特定单词的文件,string,bash,search,grep,String,Bash,Search,Grep,我需要搜索包含两个或两个以上特定单词出现次数的文件(在我的例子中为NORMAL),以便从以下文件中进行搜索: file1.txt: the NORMAL things are [ - case - case 2 a NORMAL is like [ - case 3 - case 4 ] ] the NORMAL things are [ - case - case 2

我需要搜索包含两个或两个以上特定单词出现次数的文件(在我的例子中为
NORMAL
),以便从以下文件中进行搜索:

file1.txt

the NORMAL things are [

    - case
    - case 2
    
    a NORMAL is like [

        - case 3
        - case 4
        
    ]
    
]
the NORMAL things are [

    - case
    - case 2
    
    a DIFFERENT is like [

        - case 3
        - case 4
        
    ]
    
]
the NORMAL things are [

    - case
    - case 2
    
]
file2.txt

the NORMAL things are [

    - case
    - case 2
    
    a NORMAL is like [

        - case 3
        - case 4
        
    ]
    
]
the NORMAL things are [

    - case
    - case 2
    
    a DIFFERENT is like [

        - case 3
        - case 4
        
    ]
    
]
the NORMAL things are [

    - case
    - case 2
    
]
file3.txt

the NORMAL things are [

    - case
    - case 2
    
    a NORMAL is like [

        - case 3
        - case 4
        
    ]
    
]
the NORMAL things are [

    - case
    - case 2
    
    a DIFFERENT is like [

        - case 3
        - case 4
        
    ]
    
]
the NORMAL things are [

    - case
    - case 2
    
]
它只能找到file1.txt

我尝试了一个简单的
grep

grep -Ri "*NORMAL*NORMAL*" .
但它不起作用

感谢使用打印匹配计数:

grep -c 'PATTERN' file(s)
在您的情况下,还需要第二个
grep-Pv
或类似于按匹配数筛选的内容(此处排除匹配数为0或1的文件):

这里,
:[01]
后跟0或1(选择0或1个匹配项)。
$
:行尾

另请参见:

-c
--计数
抑制正常输出;而是为每个输入文件打印匹配行的计数。使用-v(--inverse match)选项,计数 不匹配的行。(-c由POSIX指定。)

-p
--perl regexp
将模式解释为与Perl兼容的正则表达式(PCRE)

-v
--反向匹配
反转匹配的意义,以选择不匹配的线。(-v由POSIX指定。)


(从)

如果不希望递归搜索:

grep -lzE '(NORMAL).*\1' files*
grep -rlzE '(NORMAL).*\1' .
如果您确实希望递归搜索:

grep -lzE '(NORMAL).*\1' files*
grep -rlzE '(NORMAL).*\1' .
此命令在当前目录中递归检查文件,该文件中包含
NORMAL
,后跟
NORMAL
\1
)。这意味着它将匹配2个或更多匹配项。这只是打印文件名,请删除
-l
以打印内容+文件名

-l
:仅当与
grep

匹配时,才会打印文件名
-z
:数据行以0字节结束,而不是换行符
-E
:使用扩展正则表达式
-r
:递归

fgrep-c'NORMAL'文件*| awk-F:“'$NF>=2{print}”

file1.txt:2

如果您也想打印搜索结果,那么

fgrep-c'NORMAL'文件*| awk-F:“$NF>=2{print}”| grep NORMAL$(awk-F:“{print$1}”)

正常情况是[

法线类似于[

使用grep-o选项:

例:

现在,它可以与if-claus一起使用:

if [ `grep -o NORMAL file1.txt | wc -l` -ge 2 ];then echo "Count is greater than or equal to 2";else echo "Count is less than 2";fi

关于您搜索的模式,标题与您的描述相矛盾。它是否只是
NORMAL
或任何带有
NORMAL
的行,只有在下一行和上一行为空或只有空格字符或是文件边界时才是。当它出现在
fooonormalbar
中时,NORMAL匹配吗?如果您要查找的rtsing是作为
foo.bar
而不是
NORMAL
foo.bar
是否与
fooXbar
匹配?只是想知道你是否需要完全或部分匹配以及regexp或字符串匹配。我想你会想要完整的单词字符串匹配,但到目前为止,大多数答案都使用部分匹配,其中只有一个使用了字符串匹配,其余的使用regexp匹配。