最初の一致のみをGrepして停止する質問する

最初の一致のみをGrepして停止する質問する

私は、最初の一致だけを返すことを期待して、次の引数で grep を使用してディレクトリを再帰的に検索しています。残念ながら、1 つ以上が返されます。実際、最後に調べたときは 2 つでした。引数が多すぎるようです。特に、希望する結果が得られないのは残念です。:-/

# grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/directory

戻り値:

Pulsanti Operietur
Pulsanti Operietur

おそらく grep はこれを行うための最善の方法ではないでしょうか? 教えてください。どうもありがとうございます。

ベストアンサー1

-m 1は、任意のファイルで最初に一致したものを返すことを意味します。ただし、他のファイルでは引き続き検索が行われます。また、同じ行に 2 つ以上の一致がある場合は、すべてが表示されます。

head -1この問題を解決するには以下を使用できます:

grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -1

各 grep オプションの説明:

-o, --only-matching, print only the matched part of the line (instead of the entire line)
-a, --text, process a binary file as if it were text
-m 1, --max-count, stop reading a file after 1 matching line
-h, --no-filename, suppress the prefixing of file names on output
-r, --recursive, read all files under a directory recursively

おすすめ記事