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.
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)