Nedislav Denev
Nedislav Denev

Reputation: 13

How to batch convert timestamp to human date in filename?

I have a set of files with the following filename format <epochtimestamp>.topic-of-post.md, for example 1436310000.server-3-2-1.md.

I need to batch convert the timestamp part to human readable date in the format of YYYY-MM-DD, example 2014-10-14.token-revocation.md

How could I go about automating this process on a Windows system? I have Cygwin installed and some basic knowledge of bash scripting.

Upvotes: 1

Views: 1388

Answers (3)

iamauser
iamauser

Reputation: 11479

   # Get each file under the current directory 
   for f in *.md; 
    do 
      # Get the date portion of the file name
      orig_date=$(echo "${f%%.*}"); 
      # convert it to a human readable format
      cnv_date="$(date -d@$orig_date +%Y-%m-%H)"; 
      # rename
      rename "${orig_date}.server-3-2-1" "${cnv_date}.token-revocation" $f;  
    done

This works for me on a GNU bash-4.2.26 and rename-2.23.2

If you don't have rename, you can use the mv command.

mv  "${orig_date}.server-3-2-1.md" "${cnv_date}.token-revocation.md"

or

mv "$f" "${cnv_date}.token-revocation.md"

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247012

With the Perl rename command, you can do

rename 'use Time::Piece; s/(^\d+)/my $t = localtime($1); $t->ymd/e' [0-9]*.md

Upvotes: 1

Paul Hodges
Paul Hodges

Reputation: 15368

If it matters, the epoch stamp you gave doesn't match the date you used.

$: date -d@1436310000 +'%Y-%m-%d'
2015-07-07

Loop through each file, slice out the epoch, convert to the new format, then rename it. Show us what you tried if it gives you trouble.

Upvotes: 0

Related Questions