3

我有一个这样的文件:

XX1, 1.1,24.08.1994 13:00:00, 111,112,113
XX2, 1.2,24.08.1994 13:30:00, 121,122,123
XX3, NaN,22.08.1995 15:00,    131,132,133

所以时间格式不一致。有些行的时间类似于 hh:mm:ss,有些行的时间格式为 hh:mm。我想删除秒并获得这样的文件:

XX1, 1.1,24.08.1994 13:00, 111,112,113
XX2, 1.2,24.08.1994 13:30, 121,122,123
XX3, NaN,22.08.1995 15:00, 131,132,133

到目前为止我尝试的是

#!/bin/bash
sed 's@,\(..\):\(..\):\(..\) @,\1:\2 @' < time_fault > ./time_corrected

#!/usr/bin/awk -f
BEGIN { RS="," ; FS=":"; ORS=","}
{ getline str
gsub(/*..:..:..*/,  $1":"$2 str) > time_corrected }

但两者都没有工作。

4

7 回答 7

4

你几乎明白了。

sed 's@\(..\):\(..\):\(..\)@\1:\2@'

XX1, 1.1,24.08.1994 13:00, 111,112,113
XX2, 1.2,24.08.1994 13:30, 121,122,123
XX3, NaN,22.08.1995 15:00,    131,132,133
于 2013-02-04T11:12:27.173 回答
2

看看这个,如果它适合你:

根据您的示例输入,这应该有效:

awk -F, 'split($0,a,":")>2{gsub(/:[0-9][0-9],/,",")}1' file

测试

kent$  echo "XX1, 1.1,24.08.1994 13:00:00, 111,112,113
XX2, 1.2,24.08.1994 13:30:00, 121,122,123
XX3, NaN,22.08.1995 15:00,    131,132,133"|awk -F, 'split($0,a,":")>2{gsub(/:[0-9][0-9],/,",")}1'
XX1, 1.1,24.08.1994 13:00, 111,112,113
XX2, 1.2,24.08.1994 13:30, 121,122,123
XX3, NaN,22.08.1995 15:00,    131,132,133
于 2013-02-04T11:07:04.230 回答
2

sed需要一个捕获组:

sed -re 's/([0-9]{2}:[0-9]{2}):[0-9]{2},/\1,/' -e 's/, +/, /g' file
XX1, 1.1,24.08.1994 13:00, 111,112,113
XX2, 1.2,24.08.1994 13:30, 121,122,123
XX3, NaN,22.08.1995 15:00, 131,132,133

也许awk更好.. 如果需要,仅在第三个字段上应用替换,否则从第四个字段中删除额外的空格:

$ awk '{if ($3~/([0-9]{2}:){2}/) sub(/:[0-9]{2},/,",",$3);else sub(/ */,"",$4)}1'
XX1, 1.1,24.08.1994 13:00, 111,112,113
XX2, 1.2,24.08.1994 13:30, 121,122,123
XX3, NaN,22.08.1995 15:00, 131,132,133
于 2013-02-04T11:13:22.343 回答
2

我稍微调整了你的sed命令:

$ sed 's/ \(..:..\)[^,]*/ \1/g' file
XX1, 1.1,24.08.1994 13:00, 111,112,113
XX2, 1.2,24.08.1994 13:30, 121,122,123
XX3, NaN,22.08.1995 15:00,    131,132,133
于 2013-02-04T11:14:02.190 回答
2

单程:

 awk -F, '{$3=substr($3,0,16);}1' OFS=, file
于 2013-02-04T11:41:58.107 回答
1
awk -F, '{OFS=","}length($3)>16{$3=substr($3,0,16)}1' your_file

测试如下:

> cat temp
XX1, 1.1,24.08.1994 13:00:00, 111,112,113
XX2, 1.2,24.08.1994 13:30:00, 121,122,123
XX3, NaN,22.08.1995 15:00,    131,132,133

> awk -F, '{OFS=","}length($3)>17{$3=substr($3,0,16)}1' temp
XX1, 1.1,24.08.1994 13:00, 111,112,113
XX2, 1.2,24.08.1994 13:30, 121,122,123
XX3, NaN,22.08.1995 15:00,    131,132,133
于 2013-02-04T11:25:08.263 回答
0

回答非常具体的标题:“从时间中删除秒数(awk,sed)”

删除:..模式的第二次出现对我有用:

是:13:06:20

sed 's/:../ /2'

现在:13:06

于 2021-06-25T13:23:32.763 回答