在不使用 date -d 的情况下从 csv 文件更改日期和时间格式

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

G-M*_*ca' 5

一个纯 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, ":") 将时间分为小时、分钟和秒。
  • 每小时做一些数学运算;例如,12:42 AM 是 24 小时制中的 00:42。当然 PM 会增加 12 个小时。
  • 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:

  • Type the above multi-line command, and, at the end of the last line (right after }'), 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).
  • Same as the above, but after }', say < and a filename.  (You can process only one file at a time this way.)
  • Create a script file. 
    • The first line should be #!/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.)
    • Then put the above code starting at line?2.
    • At the end of the last line (right after }'),  put?"$@"?(including the quotes).
    • Save the file.  Let’s assume that you call the script gman.
    • Type chmod +x gman.
    • Type ./gman followed by either a list of filenames and/or wildcards, or by < and a single filename.


fpm*_*phy 3

这是一种方法(假设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)