[英]Convert format HH:MM:SS to seconds in a column with AWK
i have a table 我有一张桌子
RMA###Order###FR2345###00:56:10###AK234
FWA###working###FR1345###00:30:20###DE432
HQP###cat1###FR6798###1:00:20:40###TI685
i need replace the field DD:HH:MM:SS to seconds 我需要将字段DD:HH:MM:SS替换为秒
RMA###Order###FR2345###3370###AK234
FWA###working###FR1345###1820###DE432
HQP###cat1###FR6798###87640###TI685
the table is separate by '###' but the field is by ':' 该表由'###'分隔,但该字段由':'
i ussing 我用
echo "1:00:20:40" | awk -F: '{ print ($1 * 86400)+($2 * 3600) + ($3 * 60) + $4 }'
87640
to convert 转换
and to separate the table 并分开桌子
awk -F, 'BEGIN {FS=OFS="###"}
but how separate the field by ':' and convert to seconds in the same script? 但是如何用':'分隔字段并在同一脚本中转换为秒?
If you put this into a.awk 如果您将其放入a.awk
BEGIN {
OFS = FS = "###"
}
{
b = split($4,a,":")
if (b == 4) {
print $1, $2, $3, (a[1] * 86400)+(a[2] * 3600) + (a[3] * 60) + a[4], $5
} else {
print $1, $2, $3, (a[1] *3600) + (a[2] * 60) + a[3], $5
}
}
And then run 然后跑
awk -f a.awk foo.txt
You will get the desired output: 您将获得所需的输出:
RMA###Order###FR2345###3370###AK234
FWA###working###FR1345###1820###DE432
HQP###cat1###FR6798###87640###TI685
You can use the split
function: 您可以使用
split
函数:
awk '{ split($0,a,":"); print (a[1]*86400)+(a[2]*3600)+(a[3]*60)+a[4] }' <<< '1:00:20:40'
87640
So you don't mess with FS
这样您就不会迷恋
FS
I propose this solution, 我提出这个解决方案,
awk 'BEGIN {
FS=OFS="###";
split("1 60 3600 86400", vconv, " ");
}
{
n=split($4,vtime,":")
seconds = 0;
for(i=1; i<=n; i++){
seconds += vconv[i] * vtime[n-i+1];
}
$4 = seconds;
print;
}' input
you get: 你得到:
RMA###Order###FR2345###3370###AK234 FWA###working###FR1345###1820###DE432 HQP###cat1###FR6798###87640###TI685
another awk
另一个
awk
$ awk 'BEGIN{FS=OFS="###"}
{n=split($4,t,":");
s=0;
if(n==4)s=24*t[1];
s=((s+t[n-2])*60+t[n-1])*60+t[n]; $4=s}1' file
RMA###Order###FR2345###3370###AK234
FWA###working###FR1345###1820###DE432
HQP###cat1###FR6798###87640###TI685
[root@test /tmp]$ awk 'BEGIN {FS=OFS="###"}{s=split($4,t,":");$4=t[s]+t[s-1]*60+t[s-2]*3600+t[s-3]*86400}1' file.txt
RMA###Order###FR2345###3370###AK234
FWA###working###FR1345###1820###DE432
HQP###cat1###FR6798###87640###TI685
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.