I've just started using bash and I've asked this question about an issue that I had using the loop 'while' with 'grep': grep issues when using two files - I've tried everything. I was told to use 'awk' instead of 'grep' in looping due to the following issues https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice Replacing 'grep' in loop for 'awk' indeed worked. However, I realized that I need an output that saves not only the matched line but also 1 line before and 2 lines after. I googled it, but I couldn't find a way to do it. Anyone knows how I can save lines after and before in 'awk'?
Thank you advance
Suppose you want the line before 29 and two after in the output of seq 40
(that outputs 40 lines counting from 1 when supported in your environment).
You can use awk
with
seq 40 | awk 'printnext>0 {print; printnext--}
/29/ {print previous;print; printnext=2;}
{previous=$0}'
You should look what options your grep
is supporting:
seq 40 | grep -B1 -A2 "29"