8

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>
  • 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 '14 at 16:46
  • XML was only used for the example, text may be any format – DJ180 Feb 14 '14 at 17:08
10
awk -v n=3 '/<Car>/ && !--n {getline; print; exit}'

Or:

awk '/<Car>/ && ++n == 3 {getline; print; exit}'

To pass the search pattern as a variable:

PATTERN='<car>' awk -v n=3 '
  $0 ~ ENVIRON["PATTERN"] && ++n == 3 {getline; print; exit}'

Here using ENVIRON instead of -v as -v expands backslash-escape sequences and backslashes are often found in regular expressions (so would need to be doubled with -v).

  • How to pass the search pattern also as a variable in the above command – WanderingMind May 17 '16 at 14:10
  • @WanderingMind, see edit. – Stéphane Chazelas May 17 '16 at 17:04
4

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

With GNU awk you can do:

gawk -v RS='</Car>' 'NR==3 && $0=$2' inputFile
1

Here's another way with sed:

sed -n '/<Car>/{x;/.\{2\}/{x;$!{n;p};q};s/.*/&./;x}' infile

This is using the hold space to count.
Each time it encounters a line matching <Car> it exchanges buffers and checks if there are exactly N-1 occurrences of a character in the hold buffer. If the check is successful it exchanges again, and if not on the last line, it pulls in the next line and prints the pattern space then quits. Otherwise it just adds another . char to the hold space and exchanges back.

0

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.

  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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