익명 03:29

Print the second occurrence in a text file and below

Print the second occurrence in a text file and below

Suppose you have a file:

12
234
bingo
1
bingo
572
22

How to print the file starting from the second occurrence of "bingo"? (Or Nth.) Like cat, but only part of the file. Like tail +3, but the line number cannot be hardcoded. The output should be:

bingo
572
22

As a terrible hack, I came up with this to get the 2nd occurrence and below:

grep --after-context=999999999 'bingo' file.txt | tail +2 | grep --after-context=999999999 'bingo'

But this is terribly inefficient, and doesn't scale well to the N-th occurrence.



Top Answer/Comment:
$ perl -ne '$found++ if /^bingo/; print if $found >=2' t.txt
bingo
572
22

I didn't notice Kamil Maciorowski's solution when writing this but this is pretty much a direct perl equivalent to Kamil's awk solution in a comment above. Perl was partially inspired by awk so it's no surprise the obvious solutions are almost identical.

Perl is pretty much guaranteed to be present on almost all Linux distributions. So 99% of readers won't need to install anything to use this. On minimal distributions that typically use busybox and lack perl, you'd probably have to use the busybox implementation of awk.

상단 광고의 [X] 버튼을 누르면 내용이 보입니다