how to change date-format in a log file using bash, avoiding while loop

后端 未结 3 785

This is not a new question here and here, but the details make it differ.

My input log file looks like:

TEMP MON -=- Sat Aug 15 02:20:24 EEST 2020 -=-          


        
相关标签:
3条回答
  • 2021-01-13 15:02

    Using core module Time::Piece in Perl:

    perl -MTime::Piece -pe 's/-=-\s+\K(.*)(?=\s+-=-)/convert($1)/e;
      sub convert {
        $s = $_[0];
        $s =~ s/\s+EEST\s+/ /;
        $t = Time::Piece->strptime($s, "%a %b %d %T %Y");
        $res = $t->strftime("%Y-%m-%d_%H:%M:%S");
        "$res EEST"
     }' file
    
    0 讨论(0)
  • 2021-01-13 15:10

    You may use this awk solution:

    awk 'BEGIN {
       FS=OFS=" -=- "
    }
    {
       cmd = sprintf("TZ=EET date -d \"%s\" +\"%Y-%m-%%d_%T %Z\"", $2);
       if ((cmd | getline output) > 0)
          $2 = output
       close(cmd)
    } 1' file
    
    TEMP MON -=- 2020-08-15_02:20:24 EEST -=- 48.6
    TEMP MON -=- 2020-08-15_02:20:50 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:13 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:44 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:45 EEST -=- 48.6
    TEMP MON -=- 2020-08-15_02:21:52 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:53 EEST -=- 48.6
    TEMP MON -=- 2020-08-15_02:21:54 EEST -=- 49.6
    TEMP MON -=- 2020-08-15_02:21:56 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:57 EEST -=- 49.1
    
    0 讨论(0)
  • 2021-01-13 15:13

    With awk using only string functions, you can avoid calling the GNU awk datetime functions or the external command date, as we want to modify only the month and re-order the data.

    > cat tst.awk
    BEGIN { OFS=FS="-=-" }
    {
        split($2, arr, " ")
        m=(index("JanFebMarAprMayJunJulAugSepOctNovDec", arr[2])+2)/3
        $2=sprintf(" %04d-%02d-%02d_%s %s ", arr[6], m, arr[3], arr[4], arr[5])
        print
    }
    

    Usage:

    > awk -f tst.awk file
    TEMP MON -=- 2020-08-15_02:20:24 EEST -=- 48.6
    TEMP MON -=- 2020-08-15_02:20:50 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:13 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:44 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:45 EEST -=- 48.6
    TEMP MON -=- 2020-08-15_02:21:52 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:53 EEST -=- 48.6
    TEMP MON -=- 2020-08-15_02:21:54 EEST -=- 49.6
    TEMP MON -=- 2020-08-15_02:21:56 EEST -=- 49.1
    TEMP MON -=- 2020-08-15_02:21:57 EEST -=- 49.1
    
    0 讨论(0)
提交回复
热议问题