LoginSignup
iku46495963
@iku46495963

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Group単位にNoごとの実行時間および test単位の最大時間を取得

awkで以下の元CSVファイルからtest単位にNoごとの実行時間および
test単位の最大時間を取得するにはどうすればよいでしょうか

(元のCSV)
テスト,NO,開始日時,終了日時
test1,#1,2024/01/01 11:00:00,2024/01/01 11:00:00
test1,#2,2024/01/01 12:00:00,2024/01/01 12:00:01
test1,#3,2024/01/01 12:01:00,// ::**
test1,#4,
// ::,****//** ::**
test2,#1,2024/01/01 12:01:00,2024/01/01 12:01:03
test2,#2,2024/01/01 12:03:01,2024/01/02 13:03:01
test2,#3,2024/01/03 22:01:00,****// ::**
test3,#1,2024/01/01 11:10:00,2024/01/01 11:10:06
test3,#2,2024/01/01 11:11:00,2024/01/01 11:12:00
test3,#3,2024/01/01 11:13:00,2024/01/01 11:13:40
test3,#4,2024/01/01 11:15:00,2024/01/01 11:16:00

(想定結果CSV)
test1,1
test2,3600
test3,60

0

1Answer

下記のawkスクリプトで実現できます。

mktime関数を使うためgawkコマンドを使います。スクリプトの1行目のパスを環境に合わせて変更してください。

sample.awk
#!/opt/homebrew/bin/gawk -f

function str2datetime(str)
{
    split(str, array, /[:\/]/)
    start_str = array[1] " " array[2] " " array[3] " " array[4] " " array[5] " " array[6]
    #print start_str
    return mktime(start_str)
}

BEGIN {
    FS = ","
}

{
    #print $1 "|" $2 "|" $3 "|" $4

    start_datetime = str2datetime($3)
    end_datetime = str2datetime($4)
    duration = end_datetime - start_datetime
    #print start_datetime, end_datetime, duration

    if ( duration > 0 ) {
        if ( test[$1] < duration ) test[$1] = duration
    }
}

END {
    for ( key in test ) {
        print key "," test[key]
    }
}

使い方

  • sample.awkに実行権限を付与する
  • スクリプトの引数にcsvファイルを指定する
$ chmod +x ./sample.awk
$ ./sample.awk a.csv
test1,1
test2,90000
test3,60 
0

Your answer might help someone💌