BASHの3行と2行の比較

BASHの3行と2行の比較

次のテキストファイルがあります。

2014-11-24 12:59:42.169 101.0.0.0 source
2014-11-24 12:59:40.375 104.156.80.0 destination
2014-11-24 12:59:36.729 104.219.48.0 destination
2014-11-24 12:59:40.377 104.37.160.0 source
2014-11-24 12:58:58.902 107.188.128.0 both
2014-11-24 12:59:06.456 107.188.128.0 source
2014-11-24 12:59:06.840 107.192.0.0 both
2014-11-24 12:59:42.043 107.192.0.0 destination
2014-11-24 12:58:58.904 107.192.0.0 source
2014-11-24 12:59:55.488 111.0.0.0 both
2014-11-24 12:59:30.007 111.0.0.0 destination
2014-11-24 12:59:33.209 108.175.32.0 destination
2014-11-24 12:59:06.841 108.175.32.0 source
  • IP 107.188.128.0の場合、タグは次のとおりです。両方とソース、ちょうど次のように表示したいと思います。両方
  • IP 107.192.0.0の場合、タグは次のとおりです。ターゲットとソースの両方、ちょうど次のように表示したいと思います。両方
  • IP 111.0.0.0の場合、タグは次のとおりです。両方と目的地、ちょうど次のように表示したいと思います。両方
  • IP 107.192.0.0の場合、タグは次のとおりです。目的地とソース、ちょうど次のように表示したいと思います。両方

私が望む出力は次のようになります。

2014-11-24 12:59:42.169 101.0.0.0 source
2014-11-24 12:59:40.375 104.156.80.0 destination
2014-11-24 12:59:36.729 104.219.48.0 destination
2014-11-24 12:59:40.377 104.37.160.0 source
2014-11-24 12:59:06.456 107.188.128.0 both
2014-11-24 12:59:42.043 107.192.0.0 both
2014-11-24 12:59:55.488 111.0.0.0 both
2014-11-24 12:59:33.209 108.175.32.0 both

IPに一致する最新の日時を出力します。

私が試したことは次のとおりです。

awk '{print $3}' input.txt | sort -u | while read line

do 
grep $line input.txt | head -1 
done

ただし、IP 108.175.32.0では機能しません。

このソリューションは次のとおりです。

  sed '
      N
      s/\([0-9.]\)\s\S\+\n.*\1\s\S\+$/\1 both/
      t
      P
      D
      ' input.txt

しかし、これは効果があります。ただ108.175.32.0へ。

awk一度に希望の出力を使用または取得できますかsed?私はこの時点で詰まった。

ベストアンサー1

この質問は次のようになります。ここ若干修正済み:

| sed '
    :1
    N    #add next line
    s/\([0-9.]\+\)\s\S\+\n.*\s\1\s\S\+$/\1 both/
    t1   #go to point 1 if exchange took place
    P    #print first line from two
    D    #remove first line, return to start
    '

おすすめ記事