如果您想将所有内容集中在一个命令中,请尝试此操作awk
awk '/search/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>f-3 && i<f+3) print a[i]}' file
Run Code Online (Sandbox Code Playgroud)
怎么运行的:
awk '
/search/ { # Is pattern found
f=NR} # yes, store the line number (it will then store only the last when all is run
{
a[NR]=$0} # Save all lines in an array "a"
END {
while(i++<NR) # Run trough all lines once more
if (i>f-3 && i<f+3) # If line number is +/- 2 compare to last found pattern, then
print a[i] # Printe the line from the array "a"
}' file # read the file
Run Code Online (Sandbox Code Playgroud)
更灵活的解决方案来处理before和after
awk '/fem/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>=f-before && i<=f+after) print a[i]}' before=2 after=2 file
Run Code Online (Sandbox Code Playgroud)