How to combine grep with multiple arguments and different output switches

grepregular expression

I want to grep with multiple arguments where i want to show lines in the order they appear in my source file before one argument and lines after the other argument , i e combine:

grep -A5 onestring foo.txt

and

grep -B5 otherstring foo.txt

How can this be achieved?

Best Answer

In bash, ksh or 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

This takes O(n) time, given that grep outputs already sorted things. If process substitution is unavailable, either create temp files manually or use the O(n lgn) ( grep -nA5 onestring foo.txt; grep -nB5 otherstring foo.txt ) | sort -gu.

With grep -H we need to sort it in a more verbose way (thanks to 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)
Related Question