Joh*_*ruz 5 text-processing date csv
我有一个.csv文件包含
Data1|Data2|10/24/2017 8:10:00 AM
Run Code Online (Sandbox Code Playgroud)
我想将第 3 列的日期和时间格式更改如下:
从10/24/2017 8:10:00 AM
(12 小时)到20171024 08:10:00
(24 小时)。
不使用 -d
一个纯 awk 解决方案(不分叉date
命令):
awk -F'|' -vOFS='|' '
function fail() {
printf "Bad data at line %d: ", NR
print
next
}
{
if (split($3, date_time, " ") != 3) fail()
if (split(date_time[1], date, "/") != 3) fail()
if (split(date_time[2], time, ":") != 3) fail()
if (time[1] == 12) time[1] = 0
if (date_time[3] == "PM") time[1] += 12
$3 = sprintf("%.4d%.2d%.2d %.2d:%.2d:%.2d", date[3], date[1], date[2], time[1], time[2], time[3])
print
}'
Run Code Online (Sandbox Code Playgroud)
-F'|'
除了打破了输入线的竖条进$1
,$2
,$3
,等...split($3, date_time, " ")
将日期/时间字段分为三部分:日期、时间和 AM/PM 指示器。如果没有三个部分,则发出错误消息并跳过该行。split(date_time[1], date, "/")
将日期拆分为月、日和年。split(date_time[2], time, ":")
将时间分为小时、分钟和秒。sprintf
必要时重新组合的年,月,日,小时,分钟和秒,用前导零。将此分配给使用$3
重新格式化的日期/时间重建输入行;然后我们打印出来。Feature:如果输入有超过三个字段;例如,
Data1|Data2|10/24/2017 8:10:00 AM|Data4|Data5
Run Code Online (Sandbox Code Playgroud)
this script will preserve those extra field(s).
Usage:? A few minor variations:
}'
), put the name(s) of file(s) you want to process.
You can (of course) use wildcards (e.g., *.csv
) here,
in addition to or instead of filename(s).}'
, say <
and a filename.
(You can process only one file at a time this way.)#!/bin/sh
.?
(Or, if you prefer, you can use #!/bin/bash
?or?#!/usr/bin/env bash
.
A discussion of the differences between these different “she-bang” lines,
and their relative merits and counter-indications,
is beyond the scope of this question,
but you can find plenty of discourse on the topic if you search.)}'
),
put?"$@"
?(including the quotes).gman
.chmod +x gman
../gman
followed by either a list of filenames and/or wildcards,
or by <
and a single filename.这是一种方法(假设infile
您是 CSV 文件):
#!/bin/bash
IFS='|'
while read data1 data2 datestr
do
newdatestr=$(date -d"$datestr" +"%Y%m%d %T")
printf "%s|%s|%s\n" "$data1" "$data2" "$newdatestr"
done < infile
Run Code Online (Sandbox Code Playgroud)