ziulfer
ziulfer

Reputation: 1369

how to tail the penult occurence of a pattern in a file

I know that using tail -1 I can take the last of occurence of a specific pattern in a file. But how to tail the penult? I tried tail-2 which gave me the penult and the last.

I am using bash

thanks

Upvotes: 0

Views: 294

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360103

sed -n 'x;$p' inputfile

This swaps the current line into hold space and the previous line into pattern space. On the last line, the contents of pattern space is printed (which happens to be the penultimate line.

Upvotes: 2

Marc B
Marc B

Reputation: 360702

You can chain head/tail:

tail -3|head -2

which, assuming you've got a file like this:

a
b
c
d
e

will have tail produce

c
d
e

and then head grabs

c
d

Upvotes: 2

Related Questions