Datetime to epoch conversion

前端 未结 3 1397
野性不改
野性不改 2021-01-14 03:28

I have a bash question (when using awk). I\'m extracting every single instance of the first and fifth column in a textfile and piping it to a new file with the following cod

3条回答
  •  盖世英雄少女心
    2021-01-14 04:08

    awk -F '[.[:blank:]]+' '
       # use separator for dot and space (to avoid trailing time info)
    
       {
       # for line other than header
       if( NR>1) {
          # time is set for format "YYYY MM DD HH MM SS [DST]"
          #  prepare with valuable info
          T = "20"$1 " " $2
          # use correct separator
          gsub( /[\/:]/, " ", T)
          # convert to epoch
          E = mktime( T)
    
          # print result, adding fractionnal as mentionned later
          printf("%d.%d %s\n", E, $3, $7)
          }
         else {
            # print header (line 1)
            print $1 " "$7
            }
        }
       ' test170201.rawtxt \
       > Redirected.file
    
    • self commented, code is longer for understanding purpose
    • use of gnu awk for the mktime function not available in posix or older version

    Oneliner a bit optimized here after

    awk -F '[.[:blank:]]+' '{if(NR>1){T="20"$1" "$2;gsub(/[\/:]/," ", T);$1=mktime(T)}print $1" "$7}' test170201.rawtxt
    

提交回复
热议问题