Macos – How to rename the file name with timestamp of created date by JavaScript, Perl or shell on OSX

bashjavascriptmacosshell

Could you tell me how to get timestamp of created date of file and rename the file name with it by JavaScript, Perl or shell on OSX 10.9.2?

Example:

Existing: Untitled.txt timestamp is 2014/05/03 01:01:01

New: %prefix%_Untitled_20140503_0101.txt (seconds is not necessary)

Reason:

I'm having strange things that the timestamp is changed looks by microwave/V2K technology frequently. But I have to know when it's created. because these are evidence of the matter.
Please kindly help.

Best Answer

Get the creation time of the file use stat command. The output will be in seconds (since unix epoch).

  • -n option suppresses the newline at end of output.
  • -f permits use of "printf" formatting. %B is the creation or "birth" date of the file.

    D=$(stat -nf'%B' your_file)
    

Then use date -r option to input date in seconds. The +%Y... aargument specifies the date format.

   DF=$(date -r $D '+%Y%m%d_%H%M')

The bash scripting would be something like this-:

 export PREFIX="your_prefix"
 D=$(stat -nf'%B' your_file)            # seconds since creation time of file
 DF=$(date -r $D '+%Y%m%d_%H%M')             # formatted creation date/time
 mv your_file "${PREFIX}_your_file_${DF}.txt"  # rename the file
Related Question