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 am looking to display the line 4598 in the following file. Effectively I want to display the line AFTER the nth occurrence of a match. In this case, the line after the 3rd occurrence of <Car>. How do I go about this?

share|improve this question
While it might be possible to achieve what you want using sed, awk, or even grep, it's advisable to make use of a XML parser. – devnull Feb 14 '14 at 16:46
XML was only used for the example, text may be any format – DJ180 Feb 14 '14 at 17:08
up vote 9 down vote accepted
awk -v n=3 '/<Car>/ && !--n {getline; print; exit}'


awk '/<Car>/ && ++n == 3 {getline; print; exit}'
share|improve this answer

Here's a perl one:

perl -ne 'print && exit if $c==3; $c++ if /<Car>/;' file 

With GNU grep, you can also parse its output like:

grep -A 1 -m 3 '<Car>' file | tail -n 1

From man grep:

-A NUM, --after-context=NUM
          Print NUM lines of trailing context after matching lines.  
          Places a line containing a group separator (--) between 
          contiguous  groups  of  matches.          
-m NUM, --max-count=NUM
          Stop reading a file after NUM matching lines.  
share|improve this answer

With GNU awk you can do:

gawk -v RS='</Car>' 'NR==3 && $0=$2' inputFile
share|improve this answer

Here's a simple command line solution.

grep -F -A1 '<Car>' filename | grep -E -v '<Car>|--' | tail -n +3 |head -n +1

If you change the value of +3 after tail, you can specify any nth line.

share|improve this answer
Not sure why you added the tags, sed, awk, etc. If you want a solution using a specific app, utility then you should specify this in question or title. – bsd Feb 14 '14 at 17:13

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.