grepを複数のパラメータとさまざまな出力スイッチと組み合わせる方法

grepを複数のパラメータとさまざまな出力スイッチと組み合わせる方法

ソースファイルに表示される順序で、1つのパラメータの前と別のパラメータの後に行を表示したい複数のパラメータを使用してgrepを実行したいと思います。つまり、次の組み合わせが必要です。

grep -A5 onestring foo.txt

そして

grep -B5 otherstring foo.txt

これはどのように達成できますか?

ベストアンサー1

Bash、kshまたはzshから:

sort -gum <(grep -nA5 onestring foo.txt) <(grep -nB5 otherstring foo.txt)
# Sort by general numbers, make output unique and merge sorted files,
# where files are expanded as a result of shell's command expansion,
# FIFOs/FDs that gives the command's output

これを行うには、O(Ngrep)時間、出力が揃ったことを考慮してください。プロセスの置き換えが不可能な場合は、一時ファイルを手動で作成するか、O(NLGN( grep -nA5 onestring foo.txt; grep -nB5 otherstring foo.txt ) | sort -gu

grep -Hより詳細な方法でソートする必要があります(casに感謝します)。

# FIXME: I need to figure out how to deal with : in filenames then.
# Use : as separator, the first field using the default alphabetical sort, and
# 2nd field using general number sort.
sort -t: -f1,2g -um <(grep -nA5 onestring foo.txt bar.txt) <(grep -nB5 otherstring foo.txt bar.txt)

おすすめ記事