Wednesday, February 7, 2024

[SOLVED] Prepend alphanumeric string to each file in a directory

Issue

I have some video files inside some directories within a USB Stick plugged in in my TV.

Their name is something like:

1- Lists.mp4
10- Filter Function.mp4
11- List Comprehensions.mp4
12- Zip Function.mp4
13- Stacks.mp4
2- Accessing Items.mp4
20- Dictionary Comprehensions.mp4

Since my TV sort and play them in that wrong order I would like to rename those file in something like:

a 1- Lists.mp4
b 2- Accessing Items.mp4
c 10- Filter Function.mp4
d 11- List Comprehensions.mp4
e 12- Zip Function.mp4
f 13- Stacks.mp4
g 20- Dictionary Comprehensions.mp4

in a way that my TV can play them consecutively.

How can I rename recursively each file inside those directories in a way that I can prepend an alphanumeric value a, b, c, ..., aa, ab, etc. in Bash?


Solution

Using Perl's rename (usable in any OS):

rename -n 's/\d+/sprintf "%.3d", $&/e' ./*.mp4

remove -n when happy with the output.

Output:

'001- Lists.mp4'
'002- Accessing Items.mp4'
'010- Filter Function.mp4'
'011- List Comprehensions.mp4'
'012- Zip Function.mp4'
'013- Stacks.mp4'
'020- Dictionary Comprehensions.mp4'

That way, player should play in the good order.


From comments, if you need to add the today date after the integer:

rename -n '
    BEGIN{ use POSIX; }
    s/\d+/sprintf("%.3d - %s", $&, POSIX::strftime("%F", localtime(time)))/e
' ./*.mp4


Answered By - Gilles Quénot
Answer Checked By - Pedro (WPSolving Volunteer)