0

I would like to rename a number of files that have the following formatting:

ABCD_20181102.jpg
DEDE_2_20181030.jpg

i.e usually 4 random letters, followed by an underscore and a date (year, month, day). Or 4 random letters followed by an underscore, a random number, an underscore and then a date.

I would like to rename these files to date, (random number if needed), and then random letters, like the following:

20181102_ABCD.jpg
20181030_2_DEDE.jpg
  • I am a brainlet, and whenever i have to do something similar, i usually find the answer (online), can't seem to find how to switch strings that are before/after underscores ... – badaboum Nov 2 '18 at 15:48
  • Dupe (with no upvoted answers): unix.stackexchange.com/questions/314010/… – Kusalananda Nov 3 '18 at 8:25
0

You can use Parameter expansion to extract parts of the strings. # removes from the left, % removes from the right, doubling the symbol removes the longest possible match.

#! /bin/bash
for f in ABCD_20181102.jpg DEDE_2_20181030.jpg ; do
    suffix=${f#*.}
    before_underscore=${f%%_*}
    after_underscore=${f#*_}
    after_underscore=${after_underscore%.$suffix}
    if [[ $after_underscore = *_* ]] ; then
        before2=${after_underscore%_*}
        after2=${after_underscore#*_}
        after_underscore="$after2"_"$before2"
    fi
    echo mv "$f" "$after_underscore"_"$before_underscore.$suffix"
done

Just remove the echo before mv once you have checked the script does what you need.

  • @badaboum: "Thanks" on StackExchange = upvote/accept. – choroba Nov 2 '18 at 17:52
  • sry, forgot to accept ... i don't have enough reputation to upvote :-( – badaboum Nov 3 '18 at 19:37
0

If you have Larry Wall's rename, then

rename -n -e 's/.*_.*/$2_$1/' «file list»

Remove -n to enable, if output shows that it will do it correctly. (The above only tells you what it would do, but will not do it.)

0

With mmv:

$ mmv -n '*_*.jpg' '#2_#1.jpg'
ABCD_20181102.jpg -> 20181102_ABCD.jpg
DEDE_2_20181030.jpg -> 2_20181030_DEDE.jpg

(remove the -n once you are sure it's doing the right thing).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.