Bostjan
Bostjan

Reputation: 1575

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

Upvotes: 0

Views: 1643

Answers (1)

ssemilla
ssemilla

Reputation: 3970

Check this as continuation of your code

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

Which will output:

1540809300

You can then use the output of that line to perform the renaming of your files. But I suggest if it gets to complex to just create a function or an actual script for that matter.

Here is a quick function to do just that:

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")

}

e.g. rename_ts DataExport.test_20181029183500_300.csv.gz

Upvotes: 1

Related Questions