![使用 awk 添加“:”时间格式](https://linux22.com/image/81156/%E4%BD%BF%E7%94%A8%20awk%20%E6%B7%BB%E5%8A%A0%E2%80%9C%3A%E2%80%9D%E6%97%B6%E9%97%B4%E6%A0%BC%E5%BC%8F.png)
对于名为 Lab1 的输入文件:
034023 052030
034023 022130
044023 012030
034223 022030
034123 152030
024023 152030
AWK命令
awk 'gsub(/[0-9][0-9]/,"&:",$1) gsub(/[0-9][0-9]/,"&:",$2)' Lab1
结果是:
03:40:23: 05:20:30:
03:40:23: 02:21:30:
04:40:23: 01:20:30:
03:42:23: 02:20:30:
03:41:23: 15:20:30:
02:40:23: 15:20:30:
如何防止尾随冒号?
期望的结果
03:40:23 05:20:30
03:40:23 02:21:30
答案1
awk '
{
for(i=1;i<=NF;i++){
sub(/[0-9]{4}$/,":&",$i)
sub(/:[0-9]{2}/,"&:",$i)
}
}
1
' <<<\
'034023 052030
034023 022130
044023 012030
034223 022030
034123 152030
024023 152030'
产生:
03:40:23 05:20:30
03:40:23 02:21:30
04:40:23 01:20:30
03:42:23 02:20:30
03:41:23 15:20:30
02:40:23 15:20:30
其他脚本为
1。
#!/usr/bin/awk -f
gsub(/[0-9]{4}\>/,":&") &&
gsub(/:[0-9][0-9]/,"&:")
2.
#!/usr/bin/awk -f
gsub(/[0-9]{2}\B/,"&:")
3.
#!/usr/bin/awk -f
BEGIN{
FS=OFS=""
}
/[0-9]{6} [0-9]{6}/{
$3=":"$3
$4=$4":"
$11=":"$11
$12=$12":"
print
}
4.
#!/usr/bin/awk -f
/[0-9]{6} [0-9]{6}/{
printf("%02d:%d:%s:%d:%d\n",
substr($0,0,2),
substr($0,3,2),
substr($0,5,6),
substr($0,11,2),
substr($0,13,2))
}
答案2
我目前得到的最好方法但这不是唯一的方法
[root@virt03 test]# awk 'gsub(/[0-9][0-9]/,":&",$1) gsub(/[0-9][0-9]/,":&",$2)' lab1 | sed 's/://1' | sed 's/://3'
03:40:23 05:20:30
03:40:23 02:21:30
04:40:23 01:20:30
03:42:23 02:20:30
03:41:23 15:20:30
02:40:23 15:20:30
[root@virt03 test]# cat lab1
034023 052030
034023 022130
044023 012030
034223 022030
034123 152030
024023 152030
[root@virt03 test]#