I want to search for a particular string in a certain file. If I found the string, I also want to print the line X lines before (or after) that line.
Can this with grep or awk, or do I need a combination?
I would like to have something like this, but not with all trailing/leading lines before or after a hit, only the Xth.
For example, if my input looks like:
line1 with a pattern
line2
line3
line4 with a pattern
line5
line6
line7 with a pattern
...
I e.g. want to search for the word 'pattern' and output that line + the line that is 2 lines after that, but not the line that directly follows the line with the pattern. So the desired output is:
line1 with a pattern
line3
line4 with a pattern
line6
line7 with a pattern
...
awk
is so general purpose that you can use it to solve your task but you would have to write a script. So, in this case the answer would be yes. As you already found outgrep
can handle your task to a certain extent but maybe not all of it. Why do you focus on these two tools but mentionsed
in your tags? Is your real question: Can I do this only using/combining standard GNU tools without scripting? The answer is also probably yes, too, but may be a little more tricky because of special cases: What e.g. is the desired output if the pattern is found in the first X or last X lines?