简体   繁体   中英

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, ie 100.000;8438; 06:46:12 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.

Try this:

tail -2 yourfile | head -1

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

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

Use this

tail -2 <filename> | head -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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM