簡體   English   中英

如何使用 Bash 讀取文件中的倒數第二行?

[英]How to read the second-to-last line in a file using Bash?

我有一個文件,其中最后三行如下。 我想檢索倒數第二行,即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

我不知道行號。 如何使用 shell 腳本檢索它? 在此先感謝您的幫助。

嘗試這個:

tail -2 yourfile | head -1

https://stackoverflow.com/a/7671772/5287901啟發的短 sed 單線

sed -n 'x;$p'

解釋:

  • -n安靜模式:不自動打印模式空間
  • x :交換模式空間和保持空間(保持空間現在存儲當前行,模式空間存儲上一行,如果有的話)
  • $ :在最后一行, p :打印模式空間(上一行,在這種情況下是倒數第二行)。

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

用這個

tail -2 <filename> | head -1

來自: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

您不需要所有這些,只需選擇一個。

為了澄清已經說過的話:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM