Grep for Keyword1Keyword2 但不是 Keyword1TEXTKeyword2 - 非常大的 grep

Grep for Keyword1Keyword2 but not Keyword1TEXTKeyword2 - Very large grep

我希望能够 grep 获得完全匹配结果,而不输出那些在我的搜索词之间带有文本的结果。中间是输出的一部分。例如:

egrep -i "^cat|^dog" list.txt >> startswith.txt
egrep -i "home$|house$" startswith.txt >> final.txt

我想要 return 与 cathome、cathouse、doghome、doghouse 的任何匹配项;但不是 return cathasahome、catneedsahouse 等。请注意,这些文件对我来说太大了,要在每个组合中都说 ^word1word2$。

有没有办法在 grep 或 egrep 中做到这一点。

使用一些分组来指定模式的两个部分,锚点(^$)将应用于组。

$ cat list.txt 
cathome
cathouse
catindahouse
dogindahome
doghouse
doghome
$ egrep -i "^(dog|cat)(home|house)$" list.txt 
cathome
cathouse
doghouse
doghome

您可以在 Perl 正则表达式模式下使用非捕获组尝试同样的事情(因为您不关心捕获它们):

$ grep -Pi "^(?:dog|cat)(?:home|house)$" list.txt 

不知道这是否会有所不同,但尝试一下也无妨。

您没有提供任何样本输入或预期输出,因此这是一个未经检验的猜测,但这可能就是您要查找的内容:

awk '
BEGIN {
    split("cat dog",beg)
    split("home house",end)
    for (i in beg)
        for (j in end)
            matches[beg[i] end[j]]
}
tolower([=10=]) in matches
' file

例如:

$ cat file
acathome
CatHome
catinhouse
CATHOUSE
doghomes
dogHOME
dogathouse
DOGhouse

$ awk '
BEGIN {
    split("cat dog",beg)
    split("home house",end)
    for (i in beg)
        for (j in end)
            matches[beg[i] end[j]]
}
tolower([=11=]) in matches
' file
CatHome
CATHOUSE
dogHOME
DOGhouse