43

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.

8 Answers 8

113

Try this:

tail -2 yourfile | head -1
1
  • 2
    I facepalmed at this obvious answer and the fact I had to search for it... Oct 11, 2018 at 19:55
6

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

Use this

tail -2 <filename> | head -1
0
3

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
1

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.

1
tail +2 <filename>

This prints from second line to last line.

0

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
0
tac <file> | sed -n '2p'

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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