2011-08-11 18 views
24

私は最後の3行として以下のファイルを持っています。最後から2番目の行、つまり100.000;8438; 06:46:12を取得したいとします。Bash-ファイルの最後から2番目の行を読み込む方法は?

. 
. 
. 
99.900; 8423; 06:44:41 
100.000;8438; 06:46:12 
Number of patterns: 8438 

私は行番号を知らない。シェルスクリプトを使ってどのように取得できますか?あなたの助けを前にありがとう。

答えて

75

はこれを試してみてください:

tail -2 yourfile | head -1 
+1

ありがとうございます!それは私が望むように働いた – World

+0

あなたは大歓迎です! – MattH

+3

あなたは大歓迎です! – MattH

1

この

tail -2 <filename> | head -1 
2

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 
0

すでに言われてきたものを明確にする:

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 
1

から: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 

エリックPementによって、あなたはすべてを必要としませんそれらを選択してください。

0
tac <file> | sed -n '2p' 
0

短いsedのhttps://stackoverflow.com/a/7671772/5287901

sed -n 'x;$p' 

に触発ワンライナー説明:

  • -nクワイエットモード:いけない、自動的にパターンスペースを印刷
  • x:パターンスペースを交換しますホールドスペース(ホールドスペースは現在のラインを保存し、前のスペースはパターンスペース行がある場合)
  • $:最後の行に、p:パターンスペース(この場合は前の行、最後から2番目の行)を印刷します。
関連する問題