grep -lコマンドに例外を追加するには?

grep -lコマンドに例外を追加するには?

grep -l <pattern> <file_name>where を含む行が 1 つ以上ある場合、返される単純な操作を実行するのは簡単です<file_name><file_name><pattern>

行が1つ以上ある場合は返す<exception_pattern>パターンを追加したいが、1つ以上の行がある場合は返すべきではありません。<file_name><pattern><exception_pattern>

例:

$ cat file1
Results: 1, 2, 3
OK

$ cat file2
Results: 1, 2, 3
NOK

$ grep -l Results file1
file1

$ grep -l Results file2
file2

$ grep -l Results -exception NOK file1
file1

$ grep -l Results -exception NOK file2
$
$

ベストアンサー1

GNUツールの使用:

grep -lZe Results -- "${files[@]}" | xargs -r0 grep -Le NOK --

配列は$filesファイル名のリストを保持します。

-L(別名--files-without-match)は、一致しないファイル名を印刷して正常に読み取れるGNU拡張です。したがって、最初にgrep含まれるファイルのリストを作成しResultsxargsそのファイルを2番目のファイルの引数として渡し、2番目のファイルgrepは含まれていないファイルについて報告しますNOK

リストの結果を別の配列に配置するには、bash4.4+で次のことを行う必要があります。

readarray -td '' matching_files < <(
  grep -lZe Results -- "${files[@]}" | xargs -r0 grep -LZe NOK --
)

(コマンド間でファイルのリストを渡すには、NULで区切られたレコードを使用することが重要です。)

存在するzsh

matching_files=( ${(0)"$(
  grep -lZe Results -- $files | xargs -r0 grep -LZe NOK --
)"} )

単一ファイルの場合、通常は常に次のことができます。

grep -q Results file1 && ! grep -q NOK file1 && echo file1

または、すべてのファイルパスの場合(named fileの代わりにstdinとして-解釈される特別なパスを除く):grep-

grep -qe Results -- "$file" &&
  ! grep -qe NOK -- "$file" &&
  printf '%s\n' "$file"

おすすめ記事