简体   繁体   English

如何使用 Bash 读取文件中的倒数第二行?

[英]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 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?如何使用 shell 脚本检索它? 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/5287901https://stackoverflow.com/a/7671772/5287901启发的短 sed 单线

sed -n 'x;$p'

Explanation:解释:

  • -n quiet mode: dont automatically print the pattern space -n安静模式:不自动打印模式空间
  • x : exchange the pattern space and the hold space (hold space now store the current line, and pattern space the previous line, if any) x :交换模式空间和保持空间(保持空间现在存储当前行,模式空间存储上一行,如果有的话)
  • $ : on the last line, p : print the pattern space (the previous line, which in this case is the penultimate line). $ :在最后一行, p :打印模式空间(上一行,在这种情况下是倒数第二行)。

ed and sed can do it as well. edsed也可以做到。

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来自:Eric Pement的有用 sed单线

# 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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