Reputation: 41
I want to show the 3 first lines and the 2 last lines that contain a word. I tried a grep command but it's not showing what I want.
grep -w it /usr/include/stdio.h | head -3 | tail -2
It only display the 2nd and 3nd lines that contain "it" in it.
Upvotes: 3
Views: 8745
Reputation: 860
you should try this
grep -A 2 -B 3 "it" /usr/include/stdio.h
-A = After context of 2 lines to the matching word "it"
-B = After context of 3 lines to the matching word "it"
you can also add -W if you really need a regex.
expected output:
line 1
line 2
line that contains it
line 4
line 5
line 6
Upvotes: 0
Reputation: 31
You can simply append the results of head and tail :
{ head -3 ; tail -2 ;} < /usr/include/stdio.h
Upvotes: 2
Reputation: 47099
The issue here is that tail
never receives the output of grep
, but rather only the first 3 lines of the file. To make this work reliably you either need to grep
twice, once with head
and once with tail
or multiplex the stream, e.g.:
grep -w it /usr/include/stdio.h |
tee >(head -n3 > head-of-file) >(tail -n2 > tail-of-file) > /dev/null
cat head-of-file tail-of-file
Output here:
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
The GNU C Library is distributed in the hope that it will be useful,
or due to the implementation it is a cancellation point and
/* Try to acquire ownership of STREAM but do not block if it is not
Upvotes: 2