World
World

Reputation: 2047

How to read the second-to-last line in a file using Bash?

I have a file that has the following as the last three lines. I want to retrieve the penultimate line, i.e. 100.000;8438; 06:46:12.

.
.
.
99.900; 8423;   06:44:41
100.000;8438;   06:46:12
Number of patterns: 8438

I don't know the line number. How can I retrieve it using a shell script? Thanks in advance for your help.

Upvotes: 44

Views: 83113

Answers (8)

Montassar Silini
Montassar Silini

Reputation: 11

tail +2 <filename>

This prints from second line to last line.

Upvotes: 1

paranoidduck
paranoidduck

Reputation: 71

A short sed one-liner inspired by https://stackoverflow.com/a/7671772/5287901

sed -n 'x;$p'

Explanation:

  • -n quiet mode: dont automatically print the pattern space
  • x: exchange the pattern space and the hold space (hold space now store the current line, and pattern space the previous line, if any)
  • $: on the last line, p: print the pattern space (the previous line, which in this case is the penultimate line).

Upvotes: 6

plhn
plhn

Reputation: 5263

tac <file> | sed -n '2p'

Upvotes: 0

Dario More Escamez
Dario More Escamez

Reputation: 1

To clarify what has already been said:

ec2thisandthat | sort -k 5 | grep 2012- | awk '{print $2}' | tail -2 | head -1

snap-e8317883
snap-9c7227f7
snap-5402553f
snap-3e7b2c55
snap-246b3c4f
snap-546a3d3f
snap-2ad48241
snap-d00150bb

returns

snap-2ad48241

Upvotes: 0

Chen Levy
Chen Levy

Reputation: 16358

From: Useful sed one-liners by Eric Pement

# print the next-to-the-last line of a file
sed -e '$!{h;d;}' -e x              # for 1-line files, print blank line
sed -e '1{$q;}' -e '$!{h;d;}' -e x  # for 1-line files, print the line
sed -e '1{$d;}' -e '$!{h;d;}' -e x  # for 1-line files, print nothing

You don't need all of them, just pick one.

Upvotes: 1

janc
janc

Reputation: 31

ed and sed can do it as well.

str='
99.900; 8423; 06:44:41
100.000;8438; 06:46:12
Number of patterns: 8438
'

printf '%s' "$str" | sed -n -e '${x;1!p;};h'                     # print last line but one
printf '%s\n' H '$-1p' q | ed -s <(printf '%s' "$str")           # same
printf '%s\n' H '$-2,$-1p' q | ed -s <(printf '%s' "$str")       # print last line but two

Upvotes: 3

S B
S B

Reputation: 8384

Use this

tail -2 <filename> | head -1

Upvotes: 3

MattH
MattH

Reputation: 38247

Try this:

tail -2 yourfile | head -1

Upvotes: 117

Related Questions