2017-02-16 156 views
1

我想弄清楚如何使用ISO 8601格式的時間戳解析文件,添加一秒鐘然後將它們輸出到文件。Mac OSX Shell腳本解析ISO 8601日期並添加一秒?

我發現的所有例子並沒有真正告訴我如何用ISO 8601日期/時間字符串來做到這一點。

舉例: 讀的像次CSV: 「2017-02-15T18:47:59」(有些是正確的,有些則沒有)

,並在新文件中吐出「2017-02- 「15T18:48:00」

主要是爲了糾正一堆日期有59秒的結束時間,以達到1秒的標記。

這是我目前的進度:

#!/bin/bash 
while IFS='' read -r line || [[ -n "$line" ]]; do 
    # startd=$(date -j -f '%Y%m%d' "$line" +'%Y%m%d'); 
    # echo "$startd"; 
    startd=$(date -j -u -f "%a %b %d %T %Z %Y" $line) 
    #startd=$(date -j -f '%Y%m%d' "$line" +'%Y%m%d'); 
    echo "$startd"; 

done < "$1" 

任何幫助,將不勝感激

回答

1

這可能做的工作

perl -MTime::Piece -nlE '$f=q{%Y-%m-%dT%H:%M:%S};$t=Time::Piece->strptime($_,$f)+1;say $t->strftime($f)' < dates.txt 

如果dates.txt包含

2017-02-15T18:47:59 
2016-02-29T23:59:59 
2017-02-28T23:59:59 
2015-12-31T23:59:59 
2010-10-10T10:10:10 

以上產生

2017-02-15T18:48:00 
2016-03-01T00:00:00 
2017-03-01T00:00:00 
2016-01-01T00:00:00 
2010-10-10T10:10:11 
1

jm666's helpful perl answer將比你的基於shell循環的方法快得多。

這就是說,如果你想在MacOS你bash代碼的工作,其BSDdate實現,這裏有一個解決方案:

# Define the input date format, which is also used for output. 
fmt='%Y-%m-%dT%H:%M:%S' 

# Note: -j in all date calls below is needed to suppress setting the 
#  system date. 
while IFS= read -r line || [[ -n "$line" ]]; do 

    # Parse the line at hand using input format specifier (-f) $fmt, 
    # and output-format specifier (+) '%s', which outputs a Unix epoch 
    # timestamp (in seconds). 
    ts=$(date -j -f "$fmt" "$line" +%s) 

    # See if the seconds-component (%S) is 59... 
    if [[ $(date -j -f %s "$ts" +%S) == '59' ]]; then 
     # ... and, if so, add 1 second (-v +1S). 
     line=$(date -j -f %s -v +1S "$ts" +"$fmt") 
    fi 

    # Output the possibly adjusted timestamp. 
    echo "$line" 

done < "$1" 

注意,輸入的日期,如2017-02-15T18:47:59被解釋爲地方時間,因爲它們不包含時區信息。