renaming files; wildcard selects input, want to return wildcard value in output

I have a set of files as follows:

Q-30-09-1753.TIF
W-01-04-1753.TIF
W-31-12-1752.TIF
Y-14-12-1752.TIF

Using git bash on Windows I wish to rename the files to put the letter at the end of the filename as follows;

30-09-1753-Q.TIF
01-04-1753-W.TIF
31-12-1752-W.TIF
14-12-1752-Y.TIF

I have attempted to use the following code:

for f in *.TIF ; do 
    mv "$f" "${f//[A-Z]]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]-[A-Z]/}";
    echo "$f"
done

The first part successfully selects the files to change but the wildcard selection is literal when renaming them.

Asked By: Jack

||

I’d probably be lazy and let sed do this for me

newfilename=$(echo "${f}"|sed 's/(.)-([^.]*).TIF/2-1.TIF/')
mv "${f}" "${newfilename}"

instead of learning the probably excellent, yet separate string replacement methods of bash 🙂

By the way, if these are dates, your date format is bad for sorting. Be more ISO date format instead: YYYY-MM-DD will allow you to sort your file names according to the date correctly! (Otherwise you’ll sort by day-of-month first, then month second, and year last.)

newfilename=$(echo "${f}"|sed 's/(.)-(..)-(..)-(....).TIF/4-3-2-1.TIF/')
Answered By: Marcus Müller
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.