Bash:grep对所有行返回true

Bash:grep对所有行返回true,bash,grep,Bash,Grep,我有几行(我不知道)ẗ 知道有多少)。我通过管道将它们发送到grep。我需要找出是否所有的行都是由grep选择的。然后我需要写OK(如果他们都被选中)或NotOK。我该怎么做呢?一种方法是使用-v(--invert match)标志,它告诉grep搜索与您的模式不匹配的行 您可以将其与-q(--quiet或--silent)标志相结合,该标志告诉grep不要实际发出任何输出,如果它找到任何它将要输出的行,就成功退出 然后,您可以检查退出状态:如果有任何行与您的模式不匹配,则为零(“成功”/“真”

我有几行(我不知道)ẗ 知道有多少)。我通过管道将它们发送到
grep
。我需要找出是否所有的行都是由
grep
选择的。然后我需要写OK(如果他们都被选中)或NotOK。我该怎么做呢?

一种方法是使用
-v
--invert match
)标志,它告诉
grep
搜索与您的模式不匹配的行

您可以将其与
-q
--quiet
--silent
)标志相结合,该标志告诉
grep
不要实际发出任何输出,如果它找到任何它将要输出的行,就成功退出

然后,您可以检查退出状态:如果有任何行与您的模式不匹配,则为零(“成功”/“真”),否则为非零(“失败”/“假”)。因此:

if ... | grep -qv ... ; then
    echo Not OK
else
    echo OK
end

如果您有两个文件
file1
file2
,您可以使用以下命令检查
file1
的所有行是否都在
file2
中:

if ! grep -qvxFf file2 file1; then
  echo "All lines of file1 are present in file2'
else
  echo "Some lines of file1 are not present in file2'
fi
如果
file1
来自命令执行,则使用进程替换:

if ! grep -qvxFf file2 <(file1-command); then
  echo "All lines are present in file2'
else
  echo "Some lines are not present in file2'
fi

if!grep-qvxFf file2如果我理解正确,您当前有:

some-process-generating-lines |
grep -e 'some selection criterion'
您需要检查传入
grep
的行数是否与传出的行数相同-每个输入行是否满足选择标准

您需要能够同时计算输入和输出的行数。计数行很容易-通过
wc-l
传递输出并捕获整个结果

lines_out=$(some-process-generating-lines |
            grep -e 'some selection criterion' |
            wc -l)
算一算行数要稍微困难一些。最简单的方法是让
tee
命令将输入数据的副本创建到
grep
,然后计算:

tmpfile=$(mktemp ${TMPDIR:-/tmp}/soq.XXXXXXXX)
trap "rm -f $tmpfile; exit 1" 0 1 2 3 13 15

lines_out=$(some-process-generating-lines |
            tee $tmpfile |
            grep -e 'some selection criterion' |
            wc -l)
lines_in=$(wc -l <$tmpfile)

rm -f $tmpfile
trap 0 1 2 3 13 15

if [ "$lines_in" = "$lines_out" ]
then echo OK
else echo Not OK
fi
tmpfile=$(mktemp${TMPDIR:-/tmp}/soq.XXXXXXXX)
陷阱“rm-f$tmpfile;出口1”01 2 3 13 15
lines\u out=$(某些进程生成行|
T$tmpfile|
grep-e“某些选择标准”|
wc-l)

行_in=$(wc-l假设您的问题由以下定义:

some-process-generating-lines |
    grep -E 'some selection criterion'
如果你想数进数出,你可以这样做:
printf“aaa\nbbb\nccc\n”
只是代码生成输出的一个示例

#!/bin/bash

f() { cat "$1" | tee "$x" | grep -E "aaa|bbb" >"$y"; }

x=>( a=$(wc -l); echo "Lines in : $a") \
    y=>( b=$(wc -l); echo "Lines out: $b") \
        f <(printf "aaa\nbbb\nccc\n")

使用后没有要清理的文件。

您的问题不清楚。您在哪里搜索管道?从另一个文件?我猜了一下您想问什么-如果我误解了您的问题,请解释更多。您肯定想避免出现错误。@tripleee完成(好吧,一半,因为我发现这更不容易理解)。
f() { <"$1" tee "$x" | grep -E "aaa|bbb" >"$y"; }
$ ./script.sh
Lines out: 2
Lines in : 3