Bash – Rename and Prefix Filename with Date and Time

bashshell-script

I am trying to prefix timestamp and add an extension to files using a script.
I have file ABC which I is being renamed to ABC.txt

DIRECTORY=`find /path/to/file -type f ! -name "*.*"`
NOW=$(date +%Y-%m-%d-%H%M%S)

for file in $DIRECTORY; do

    mv "$file" "$file"_"${NOW}.txt"
    done

The output above works but as a suffix, if I switch it around

    mv "$file" "${NOW}"$file".txt"

I'm getting cannot mv: cannot move`2019-10-18-231254/path/to/file/ABC.txt': No such file or directory

I can see the issue is with the $Directory as this is calling the full path when doing the mv. Could someone please help simplify this?

Best Answer

I'd suggest avoiding the loop over the find command's output for the reasons discussed here:

Instead, consider using -execdir, with a shell one-liner to remove the path components:

#!/bin/bash

export NOW=$(date +%Y-%m-%d-%H%M%S)

find /path/to/file -type f ! -name '*.*' -execdir sh -c '
  for f; do echo mv "$f" "${NOW}_${f#./}"; done
' find-sh {} +

Remove the echo once you are happy that it is doing the right thing. Note that NOW needs to be exported so that its value is available in the sh -c subshell.

If your find implementation doesn't provide -execdir, then you can use -exec if you remove and replace the path explicitly:

find /path/to/file -type f ! -name '*.*' -exec sh -c '
  p="${1%/*}"; echo mv "$1" "$p/${NOW}_${1##*/}"
' find-sh {} \;
Related Question