首页 > 解决方案 > Convert timestamp string to UTC date in bash

问题描述

I would like to rename my files with UTC timestamp. Currently those files are names based on local time (CET), as following, where first number if timestamp:

DataExport.test_20181029183500_300.csv.gz

For a reason I can not fix that at file source itself, so I have to perform a change later on.

Currently I extracted number with following:

echo "DataExport.test_20181029183500_300.csv.gz" | cut -d"_" -f2- | cut -c1-14

But now I am stuck here, how to continue.

Thank you and best regards

标签: bashdatetimestamputc

解决方案


将此检查为您的代码的延续

date -d "$( echo "DataExport.test_20181029183500_300.csv.gz" | cut -d'_' -f2 | sed 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1-\2-\3 \4:\5:\6/g' )" +%s

这将输出:

1540809300

然后,您可以使用该行的输出来执行文件的重命名。但是我建议如果仅仅为此创建一个函数或一个实际的脚本会变得复杂。

这是一个快速的功能来做到这一点:

function rename_ts() {

    filename="$1"
    time_stamp=$(echo "$filename" | cut -d'_' -f2)
    date_fmt=$(echo "$time_stamp" | sed 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1-\2-\3 \4:\5:\6/g')
    utc=$(date -d "$date_fmt" +%s)

    mv $filename $(echo "$filename" | sed "s/$time_stamp/$utc/g")

}

例如rename_ts DataExport.test_20181029183500_300.csv.gz


推荐阅读