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 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?

<Car>
10456
</Car>
<Car>
70192
</Car>
<Car>
4598
</Car>
share|improve this question
1  
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 at 16:46
    
XML was only used for the example, text may be any format –  DJ180 Feb 14 at 17:08
add comment

4 Answers

up vote 8 down vote accepted
awk -v n=3 '/<Car>/ && !--n {getline; print; exit}'

Or:

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

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
add comment

With GNU awk you can do:

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

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. –  bdowning Feb 14 at 17:13
add comment

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.