我有一个文件 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
此处输入的日期是带有 (是耳朵,中号日,D哎呀,H我们的,中号初始,S第二)
YYYYMMDDHHMMSS
输出应该是:
DD-MM-YYYY HH:MM:SS
答案1
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
答案2
接下来将转换任何 14 位数字的字段:
awk -F, ' function form(E){
$E=substr($E,1,4) "-" substr($E,5,2) "-" substr($E,7,2) " "\
substr($E,9,2) ":" substr($E,11,2) ":" substr($E,13)
}
{ for(i=1;i<=NF;i++)
if($i ~ /[0-9]{14}/)
form(i)
print
}' OFS=, mdn.txt
答案3
如果源字符串保存在变量 s 中,那么您可以只使用 printf 和 substr ie
printf("%2d-%2d-%4d %2d:%2d:%2d", substr(s,7,2), substr(s,5,2), substr(s,1,4), substr( s,9,2), 子字符串(s,11,2), 子字符串(s,13,2) )