Shell-Script

更改 awk 命令中的日期格式

  • August 20, 2015

我有一個帶有以下範例記錄的文件 mdn.txt。

mdn.txt:

123456,2711448,1,20150214092425,20150714092425,120,20150814163821,,123,,,123,20150214092425,,123,,,123,20150214092425,,123,Y

現在我想處理我的文件的每條記錄,awk並希望更改日期欄位的格式,如下所示:

123456,2711448,1,14-02-2015 09:24:25,14-07-2015 09:24:25,120,14-08-2015 16:38:21,,123,,,123,14-02-2015 09:24:25,,123,,,123,14-02-2015 09:24:25,,123,Y

此處輸入的日期是帶有(Year, M onth , Day, Hour , M inute , S econd)的數字

YYYYMMDDHHMMSS

輸出應該是:

DD-MM-YYYY HH:MM:SS
awk 'BEGIN{ FS=OFS="," 
           n=split("4,5,7,13,19", f)   # array of input field numbers
    }
    { for(i=1; i<=n; i++) if($f[i]) $f[i] = dconv($f[i]); print 
    }
    function dconv(x) {
      YY=substr(x, 1, 4)
      mm=substr(x, 5, 2)
      dd=substr(x, 7, 2)
      hh=substr(x, 9, 2)
      nn=substr(x,11, 2)
      ss=substr(x,13, 2)
      return dd"-"mm"-"YY" "hh":"nn":"ss  
    }' file

下面,(基本上)是相同的腳本,還有一個數組(並且沒有函式)

awk 'BEGIN{ FS=OFS=","
           nf=split("4,5,7,13,19", f)                           # array of input field numbers
           nd=split(",7,2,-,5,2,-,1,4, ,9,2,:,11,2,:,13,2", d)  # array of date subfield info (in output order): prefix(out),pos(in),len(in)         
    }
    { for(i=1; i<=nf; i++){ 
          if($f[i]) {
              fmod=""
              for(j=1; j<=nd; j+=3) fmod=fmod sprintf("%s", d[j] substr($f[i], d[j+1], d[j+2]))
              $f[i] = fmod
          }
      } print
    }' file

引用自:https://unix.stackexchange.com/questions/224223