Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know that by using the "-A NUM" switch I can print specific number of trailing lines after each match. I am just wondering if it's possible to print trailing lines until a specific word is found after each match. e.g. When I search for "Word A" I want to see the line containing "Word A" and also the lines after it until the one containing "Word D".


Word A
Word B
Word C
Word D
Word E
Word F


grep -A10 'Word A'

I need this output:

Word A
Word B
Word C
Word D
share|improve this question
up vote 32 down vote accepted

It seems that you want to print lines between 'Word A' and 'Word D' (inclusive). I suggest you to use sed instead of grep. It lets you to edit a range of input stream which starts and ends with patterns you want. You should just tell sed to print all lines in range and no other lines:

sed -n -e '/Word A/,/Word D/ p' file
share|improve this answer
Any tips on how to make it exclusive (for any generic situation, not just OP's)? – 2rs2ts Jun 18 '13 at 17:18
@2rs2ts to make it exclusive, just add | sed -e '1d;$d', that is remove first and last line – holroy Jun 26 '15 at 9:54

why not use awk ?

awk '/Word A/,/Word D/' filename
share|improve this answer
sed appears to be able to do this much more efficiently if a large number of files are involved. awk may be easier to remember, but sed seems to be worth a sticky note in my brain. – JimNim Nov 24 '14 at 16:02
perl -lne 'print if /Word A/ .. /Word D/' file


cat file | perl -lne 'print if /Word A/ .. /Word D/'
share|improve this answer
+1 to counter the drive-by downvote. I'd still use sed for this, unless you need the power of Perl regular expressions to select the delimiting lines. – tripleee Jul 2 '13 at 9:32

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.