Linux 如何使用 Bash 读取文件中的倒数第二行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7022390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read the second-to-last line in a file using Bash?
提问by World
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
.
我有一个文件的最后三行如下。我想检索倒数第二行,即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.
我不知道行号。如何使用 shell 脚本检索它?在此先感谢您的帮助。
采纳答案by MattH
Try this:
尝试这个:
tail -2 yourfile | head -1
回答by S B
Use this
用这个
tail -2 <filename> | head -1
回答by janc
ed
and sed
can do it as well.
ed
并且sed
也可以做到。
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
回答by Dario More Escamez
To clarify what has already been said:
澄清已经说过的内容:
ec2thisandthat | sort -k 5 | grep 2012- | awk '{print }' | tail -2 | head -1
snap-e8317883
snap-9c7227f7
snap-5402553f
snap-3e7b2c55
snap-246b3c4f
snap-546a3d3f
snap-2ad48241
snap-d00150bb
returns
返回
snap-2ad48241
回答by Chen Levy
From: Useful sed one-linersby Eric Pement
来自:Eric Pement 的有用 sed one-liners
# 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.
您不需要所有这些,只需选择一个即可。
回答by plhn
tac <file> | sed -n '2p'
回答by paranoidduck
A short sed one-liner inspired by https://stackoverflow.com/a/7671772/5287901
受https://stackoverflow.com/a/7671772/5287901启发的简短 sed one-liner
sed -n 'x;$p'
Explanation:
解释:
-n
quiet mode: dont automatically print the pattern spacex
: 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).
-n
安静模式:不自动打印模式空间x
: 交换模式空间和保持空间(保持空间现在存储当前行,模式空间存储前一行,如果有的话)$
: 在最后一行,p
: 打印模式空间(前一行,在本例中是倒数第二行)。