如何将 grep 与多个参数和不同的输出开关结合起来

如何将 grep 与多个参数和不同的输出开关结合起来

我想使用多个参数进行 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(n) 时间,考虑到grep输出已经对事物进行了排序。如果进程替换不可用,请手动创建临时文件或使用 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)

相关内容