ubuntu 如何搜索“hello”但从查找grep文件中排除“test”

ncecgwcz  于 2023-01-16  发布在  其他
关注(0)|答案(3)|浏览(173)

我想search所有文件包含文本“hello“,但exclude结果包含“test“。

以下是示例文件:

mkdir -p /tmp/test
cd /tmp/test

echo "foo hello" > foo.txt

echo "bar world" > bar.txt
echo "test hello" >> bar.txt
echo "world hello" >> bar.txt

以下是“hello”的搜索:

# find /tmp/test -type f -name '*' -exec grep -H -i "hello" {} \;
/tmp/test/bar.txt:test hello
/tmp/test/bar.txt:world hello
/tmp/test/foo.txt:foo hello

现在我想从上面的搜索输出中排除“test”:

# find /tmp/test -type f -name '*' -exec grep -H -i "hello" {} \; | grep -v "test"
...Nothing here...

尝试其他模式:

# find /tmp/test -type f -name '*' -exec grep -H -i "hello" -v "test" {} \;
grep: test: No such file or directory
/tmp/test/bar.txt:bar world
grep: test: No such file or directory

以下是预期输出:

# find /tmp/test -type f -name '*' -exec grep [commands argumensts here] {} \;
/tmp/test/bar.txt:world hello
/tmp/test/foo.txt:foo hello

如何在文件中查找searchexclude

zlwx9yxi

zlwx9yxi1#

使用awk代替grep:

$ find test -type f -exec awk '/hello/&&!/test/{print FILENAME,$0}' {} \;
test/foo.txt foo hello
test/bar.txt world hello
iqxoj9l9

iqxoj9l92#

问题是文件路径中有test
您可以匹配:之后的内容,但只有在文件文本中没有:时才能匹配。

find /tmp/test -type f -name '*' -exec grep -H -i

示例:

/t/test  ❯❯❯ find /tmp/test -type f -name '*' -exec grep -H -i "hello" {} \; | grep -v -E ".*\:.*test"
/tmp/test/foo.txt:foo hello
/tmp/test/bar.txt:world hello
nwlqm0z1

nwlqm0z13#

您可以使用awk,它可以非常快速地解析文件内容。

#!/bin/sh

file1="grepTest1.txt"
echo "dum dum
dum hello dum
crumb test crumb
dum dum" >${file1}

file2="grepTest2.txt"
echo "dum dum
dum hello dum
dum dum" >${file2}

file3="grepTest3.txt"
echo "dum dum
dum test dum
crumb hello crumb
dum dum" >${file3}

file4="grepTest4.txt"
echo "dum dum
crumb jello crumb
crumb bellow crumb
dum test dum
dum dum" >${file4}

for file in grepTest?.txt
do
    awk -v acc="hello" -v rej="test" 'BEGIN{
        good=0 ;
    }
    {
        if( index($0, rej) != 0 ){
            good=2 ;
            exit ;
        }else{
            if( index($0, acc) != 0 ){
                good=1 ;
                line=$0 ;
            } ;
        } ;
    }
    END{
        if( good == 1 ){
            printf("%s: %s\n", FILENAME, line ) ;
        }else{
            if( good == 2 ){
                printf("REJECT: Found %s at line %s in %s.\n", rej, NR, FILENAME ) | "cat >&2" ;
            } ;
        } ;
    }' ${file}
done

给出输出

REJECT: Found test at line 3 in grepTest1.txt.
grepTest2.txt: dum hello dum
REJECT: Found test at line 2 in grepTest3.txt.
REJECT: Found test at line 4 in grepTest4.txt.

但是...请注意,3个拒绝行转到stderr。如果您将stdout重定向到一个文件,则该列表中将只有好文件的列表。

相关问题