0

スクリプト (シェル スクリプトまたは awk) を作成して、重複エントリの $1 (最初のフィールド) をすべて収集し、最後の値を使用して最後のエントリと最初のエントリの違いを見つけたり、すべての重複で値の違いに注意したいエントリ。

たとえば、私のファイルには次のエントリがあります。

counter1 is 100
counter2 is 200
counter3 is 300
counter1 is 1000
counter2 is 2000
counter3 is 3000
counter1 is 10000
counter2 is 20000
counter3 is 30000

印刷したい:

counter1 is 100
counter1 is 1000
counter1 is 10000
counter2 is 200
counter2 is 2000
counter2 is 20000
counter3 is 300
counter3 is 3000
counter3 is 30000

各カウンターにはいくつかの値がインクリメントされているため、同じカウンターの各値の違いを見つけたいと思います。

counter1 is 100
counter1 is 1000 | difference 1000-100 = 900
counter1 is 10000| difference 10000-100= 9900

重複したエントリを印刷することはできましたが、それらを束ねることはできず、ファイルと同じ順序で表示されました。

MacBook-Air:linuxscripts jimdev$ awk 'NR==FNR && a[$1]++ {b[$1];next} $1 in b' FS=" " countr.txt countr.txt 

counter1 is 100
counter2 is 200
counter3 is 300
counter1 is 1000
counter2 is 2000
counter3 is 3000
counter1 is 10000
counter2 is 20000
counter3 is 30000
4

2 に答える 2

2

これはあなたのために働きますか?

sort countr.txt | grep -v '^$'  | awk '
BEGIN { field1="different" ; firstval="0" ; }
     $1 !~ field1 { print $0 ; field1 = $1 ; firstval = $NF ; continue;}
     $1  ~ field1 { print $0 " | difference " $NF "-" firstval " = " $NF-firstval ; }'

投稿に示されているように、入力ファイルの出力は次のとおりです。

counter1 is 100
counter1 is 1000 | difference 1000-100 = 900
counter1 is 10000 | difference 10000-100 = 9900
counter2 is 200
counter2 is 2000 | difference 2000-200 = 1800
counter2 is 20000 | difference 20000-200 = 19800
counter3 is 300
counter3 is 3000 | difference 3000-300 = 2700
counter3 is 30000 | difference 30000-300 = 29700
于 2013-01-29T19:24:24.397 に答える
1

データが というファイルにあると仮定しますdata.txt。sort と awk simple if (またはパターンを使用) で取得できます。

sort data.txt | awk 'BEGIN{last = ""; value = 0;} {if ($1 == last) {print $1" is "$3" | difference "$3"-"value" = "($3-value)}else{last = $1; value = $3; print $1" is "$3;}}' -

説明: まず、「カウンター」が昇順になるように入力を並べ替えます。次に、次のAWK式を使用します。

  1. 現在のカウンターを格納する last 変数と、最初のカウンターの値の 2 つの一時変数を使用します。スクリプトの BEGIN 部​​分で初期化しAWKます: BEGIN{last = ""; value = 0;}.

ここで、各行に対して次のコードを実行します。

if ($1 == last) {
    print $1" is "$3" | difference "$3"-"value" = "($3-value);
} else {
    last = $1;
    value = $3;
    print $1" is "$3;
}

1 行目: 最初のフィールド (カウンター) をlast、最後のカウンター タグを格納する と比較して、違いを出力する必要があるかどうかを確認します。

2 行目: 現在の行に前の行と同じカウンター タグがある場合、違いを出力します。

3行目: それ以外はベースケースなので、現在のカウンタータグを保存して次の行と比較し、その値を比較して差を計算し、行を出力します。

  1. 新しい行に前の行と同じカウンター タグがある場合、値を保持し、このカウンターの最初の値との差を計算します。それ以外の場合は、新しいカウンター タグ (最後の変数) とその値 (値) を格納し、行を出力するだけです。

入力サンプルの出力は次のとおりです。

counter1 is 100
counter1 is 1000 | difference 1000-100 = 900
counter1 is 10000 | difference 10000-100 = 9900
counter2 is 200
counter2 is 2000 | difference 2000-200 = 1800
counter2 is 20000 | difference 20000-200 = 19800
counter3 is 300
counter3 is 3000 | difference 3000-300 = 2700
counter3 is 30000 | difference 30000-300 = 29700
于 2013-01-29T19:30:41.600 に答える