Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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".

context:

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

command:

grep -A10 'Word A'

I need this output:

Word A
Word B
Word C
Word D
share|improve this question

3 Answers 3

up vote 15 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

why not use awk ?

cat filename | awk '/Word A/,/Word D/'

share|improve this answer
3  
awk will accept the filename after invocation; no need for the feline... –  jasonwryan Jul 2 '13 at 4:03
    
Yea, i know. its just a habit. –  cesar Jul 2 '13 at 12:54
perl -lne 'print if /Word A/ .. /Word D/' file

or

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

 
discard

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.