Search code examples
unixunix-timestamp

Replace old timestamp with current timestamp in set of files


I have some files residing in a directory:

TESTRP_20201126220042.TAB
TESTRP_20201214145845.TAB
TESTRP_20210201145846.TAB
TESTRP_20210304134849.TAB

Here I need to replace the old timestamp with the current timestamp date +%Y%m%d%H%M%S

I tried to run the following code:

find . -type f -name '*TESTRP_*' -exec sh -c '
    now=$(date '+%Y%m%d%H%M%S')
    for pathname do
        mv "$pathname" "${TESTRP}_$now.TAB"
    done' sh {} +

But its giving me single output file _20210630083729.TAB rather than three files with updated timestamp.


Solution

  • Maybe something like

    shopt -s extglob # Turn on bash extended globbing if not already enabled
    for file in TESTRP_+([0-9]).TAB; do
        mv "$file" "${file/+([0-9])/$(date '+%Y%m%d%H%M%S')}"
        sleep 1
    done
    

    which should rename one file a second. Alternatively, add a counter after the timestamp and increment it on every file:

    shopt -s extglob
    now=$(date '+%Y%m%d%H%M%S')
    declare -i fileno=0
    for file in TESTRP_+([0-9]).TAB; do
        newts=$(printf "%s%04d" "$now" "$fileno")
        mv "$file" "${file/+([0-9])/$newts}"
        ((fileno++))
    done
    

    Or it looks like some versions of date have a %N format for nanoseconds which shouldn't result in the same timestamp in any two calls of date '+%Y%m%d%H%M%S%N'