Enigma
Enigma

Reputation: 31

Bash: Rename file name to unix timestamp of modification date

Hello I need to rename files to their unix time stamp of their modification date and append it as a prefix.

In other words I need a script to mass rename Files like

ABC.jpg

and

XYZ.png

to

1649493072000 ABC.jpg

1649493072182 XYZ.png

I also like to append a u- in front of every file that is modified this way.

SO I like to turn

ABC.jpg

and

XYZ.png

Into

u-1649493072000 ABC.jpg

u-1649493072182 XYZ.png

PS:

To all mods please note that my question is different from other questions already asked since I'm asking about the UNIX Modification timestamp of the file not the ISO date like 2022-04-09.

Upvotes: 0

Views: 1532

Answers (2)

commonpike
commonpike

Reputation: 11185

Same as the accepted answer, but I find it more readable

#!/bin/bash

find $1 -type f -exec \
bash -c '
    FILEPATH="{}"
    BASEDIR=$(dirname "$FILEPATH")
    [ "$BASEDIR" = / ] && BASEDIR=
    FILENAME=$(basename "$FILEPATH")
    TIMESTAMP=`stat -f "%m" "$FILEPATH"`;
    DATENAME=`date -r $TIMESTAMP '\''+%Y%m%d-%H%M%S'\''`-$FILENAME
    echo mv -v "$FILEPATH" "$BASEDIR/$DATENAME";
' \;
  • save it as a shell script and call it with the basedir as argument ($1)
  • this is for osx - on ubuntu, the stat command may require something like %Y instead of %m
  • renames each file by prepending yyyymmdd-hhmmss- to the filename
  • remove the echo to actually execute it

Upvotes: 0

dan
dan

Reputation: 5221

find . -type f -exec \
sh -c '
for i do
    d=$(dirname "$i")
    [ "$d" = / ] && d=
    n=${i##*/}
    echo mv "$i" "$d/u-$(stat -c %Y "$i") $n"
done' _ {} +
  • This operates recursively in the current directory (.). It only targets regular files (not directories etc). Modify -type f and other flags if needed.

  • It just prints the mv commands, so you can review them. Remove the echo to run for real.

  • We use find to list the target files, and its -exec flag to pass this list to a shell loop where we can parse and modify the filenames, including stat to get the modification time.

  • I don't know your use case, but a better solution may be to just save the output of: find . -type f -printf '%p u-%T@\n' in a file, for later reference (this prints the file path and modification time on the same line). Also, maybe a snapshot (if possible).

Upvotes: 3

Related Questions