【发布时间】:2011-08-11 07:35:44
【问题描述】:
我有一个文件,最后三行如下。我想检索倒数第二行,即100.000;8438; 06:46:12。
.
.
.
99.900; 8423; 06:44:41
100.000;8438; 06:46:12
Number of patterns: 8438
我不知道行号。如何使用 shell 脚本检索它?提前感谢您的帮助。
【问题讨论】:
我有一个文件,最后三行如下。我想检索倒数第二行,即100.000;8438; 06:46:12。
.
.
.
99.900; 8423; 06:44:41
100.000;8438; 06:46:12
Number of patterns: 8438
我不知道行号。如何使用 shell 脚本检索它?提前感谢您的帮助。
【问题讨论】:
受 https://stackoverflow.com/a/7671772/5287901 启发的短 sed one-liner
sed -n 'x;$p'
解释:
-n安静模式:不自动打印模式空间x:交换模式空间和保持空间(保持空间现在存储当前行,模式空间存储上一行,如果有)$:在最后一行,p:打印模式空间(上一行,在本例中为倒数第二行)。【讨论】:
试试这个:
tail -2 yourfile | head -1
【讨论】:
使用这个
tail -2 <filename> | head -1
【讨论】:
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
【讨论】:
发件人:Useful 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
您不需要所有这些,只需选择一个即可。
【讨论】:
澄清已经说过的话:
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
返回
snap-2ad48241
【讨论】:
tac <file> | sed -n '2p'
【讨论】: