Automator :: Remove 6 digit date from filename; append current date

automationautomatorcommand linefinderscript

I apologize in advance if this has been answered but have performed a lengthy search in hope of a solution.

I have a working Automator app that appends the current six-digit date (YYMMDD) to the end of the file name:

  • Input: Filename.txt
  • Output: Filename_181212.txt

Current bash command:

today=$(date +%y%m%d)
for f in "$@"
do
    basename=${f##*/}
    filename=${basename%.*}
    path=${f%/*}
    ext=${f##*.}
    newfilename="$filename"_"$today"
    mv "$f" "$path"/"$newfilename"."$ext"
done

This is great but after using it regularly, I have realized it would be nice not only append the current date but first check to see if a date is already appended to the filename; if so, remove it and append the current date, otherwise simply append the current date.

There two scenarios:

  1. Filename contains any date (previous/current/future) in the 6-digit format described previously preceded by an underscore (Filename_181212.txt)
  2. Filename does not contain at 6-digit date format appended to it (Filename.txt)

I realize that the solution I am hoping for will remove any six digits and its preceding "_" if it exists, whether it is a date or not.

Is it possible to precede my current bash command with something like:

if any combination of numbers exist immediately before the file
extension (".ext") AND contains exactly 6 digits AND is preceded by
an underscore ("_")

then remove the underscore plus 6 digits AND run the bash command
listed above

if not then run the bash command above

Summary
I'm trying to alleviate manually removing dates that may exist on a file name before appending the current date to them. Some files may have dates and others may not.

Best Answer

  • This should do as you requested:

    #!/bin/bash
    
    today=$(date +%y%m%d)
    
    for f in "$@"; do
    
        filebasename=${f##*/}
        filename=${filebasename%.*}
        path=${f%/*}
        ext=${f##*.}
    
        if [[ "$filename" =~ ^.*_[0-9]{6}$ ]]; then
    
            filename="$(sed -E -e 's/_[0-9]{6}$//'<<<"$filename")"
    
            newfilename="$filename"_"$today"
            mv "$f" "$path"/"$newfilename"."$ext"   
    
        else    
    
            newfilename="$filename"_"$today"
            mv "$f" "$path"/"$newfilename"."$ext"
    
        fi
    
    done
    

    Note that when used within a Run Shell Script action in an Automator workflow, you may need to add the full path to sed in the code provided, e.g.: /usr/bin/sed