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.

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 thought it would be sed -n /mymatch/,+5p but I get expected context address. At this point I am just guessing commands, nothing works! I want to grab every line that matches the regex and print that line and the line which comes 5 lines after it, globally from a file.

share|improve this question

Might be easier with awk:

awk '/foo/ {print; p[NR+5]; next}; NR in p'
share|improve this answer

Here's a brute force approach, and may not work as you expect if there's another match inside the 5 lines:

sed -n '/mymatch/ {p;n;p;n;p;n;p;n;p;n;p;}'
share|improve this answer
sed: 1: "/[A-Z][0-9]/ {p;n;p;n;p ...": extra characters at the end of p command – Gregg Leventhal Jan 24 '14 at 17:10
You needed a ; at the end. Ill make the edit – Gregg Leventhal Jan 24 '14 at 17:10

If you don't want the lines between, you can do this:

perl -lne '$a=5 if /foo/; print if $a==0||$a==5; $a--' file.txt 

or, if you prefer slurping:

perl -e '@f=<>; for($i=0;$i<=$#f;$i++){print "$f[$i]$f[$i+5]" if $f[$i]=~/foo/}' file 
share|improve this answer
I dont want the lines between, I want lines matching /regex/ and the line that comes 5 lines after the regex, not the next 5 consecutive lines. – Gregg Leventhal Jan 24 '14 at 19:27
@GreggLeventhal ah, sorry, see updated answer. – terdon Jan 24 '14 at 19: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.