Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is what I usually do on AIX:</p> <pre><code>before=2 &lt;&lt; The number of lines to be shown Before &gt;&gt; after=2 &lt;&lt; The number of lines to be shown After &gt;&gt; grep -n &lt;pattern&gt; &lt;filename&gt; | cut -d':' -f1 | xargs -n1 -I % awk "NR&lt;=%+$after &amp;&amp; NR&gt;=%-$before" &lt;filename&gt; </code></pre> <p>If you do not want the extra 2 varialbles you can always use it an a one line:</p> <pre><code>grep -n &lt;pattern&gt; &lt;filename&gt; | cut -d':' -f1 | xargs -n1 -I % awk 'NR&lt;=%+&lt;&lt;after&gt;&gt; &amp;&amp; NR&gt;=%-&lt;&lt;before&gt;&gt;' &lt;filename&gt; </code></pre> <p>Suppose I have a pattern 'stack' and the filename is flow.txt I want 2 lines before and 3 lines after. The the command will be like:</p> <pre><code>grep -n 'stack' flow.txt | cut -d':' -f1 | xargs -n1 -I % awk 'NR&lt;=%+3 &amp;&amp; NR&gt;=%-2' flow.txt </code></pre> <p>I want 2 lines before and only - the the command will be like:</p> <pre><code>grep -n 'stack' flow.txt | cut -d':' -f1 | xargs -n1 -I % awk 'NR&lt;=% &amp;&amp; NR&gt;=%-2' flow.txt </code></pre> <p>I want 3 lines after and only - the the command will be like:</p> <pre><code>grep -n 'stack' flow.txt | cut -d':' -f1 | xargs -n1 -I % awk 'NR&lt;=%+3 &amp;&amp; NR&gt;=%' flow.txt </code></pre> <p>Multiple Files - change it for Awk &amp; grep. From above for the pattern 'stack' with the filename is <strong>flow.*</strong> - 2 lines before and 3 lines after. The the command will be like: </p> <pre><code> awk 'BEGIN { before=1; after=3; pattern="stack"; i=0; hold[before]=""; afterprints=0} { #Print the lines from the previous Match if (afterprints &gt; 0) { print FILENAME ":" FNR ":" $0 afterprints-- #keep a track of the lines to print after - this can be reset if a match is found if (afterprints == 0) print "---" } #Look for the pattern in current line if ( match($0, pattern) &gt; 0 ) { # print the lines in the hold round robin buffer from the current line to line-1 # if (before &gt;0) =&gt; user wants lines before avoid divide by 0 in % # and afterprints =&gt; 0 - we have not printed the line already for(j=i; j &lt; i+before &amp;&amp; before &gt; 0 &amp;&amp; afterprints == 0 ; j++) print hold[j%before] if (afterprints == 0) # print the line if we have not printed the line already print FILENAME ":" FNR ":" $0 afterprints=after } if (before &gt; 0) # Store the lines in the round robin hold buffer { hold[i]=FILENAME ":" FNR ":" $0 i=(i+1)%before } }' flow.* </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload