Bash – Add 0 in the middle of a filename

bashrenameshell

$ ls
pro2e_u01_txt_vocabulaire_11_descriptiveadjectives.mp3
pro2e_u01_txt_vocabulaire_12_nationality.mp3
pro2e_u01_txt_vocabulaire_1_campus.mp3
pro2e_u01_txt_vocabulaire_2_personnes.mp3
pro2e_u01_txt_vocabulaire_3_presentations.mp3
pro2e_u01_txt_vocabulaire_4_identifier.mp3
pro2e_u01_txt_vocabulaire_5_bonjouraurevoir.mp3
pro2e_u01_txt_vocabulaire_6_commentcava.mp3
pro2e_u01_txt_vocabulaire_7_expressionspolitesse.mp3

I would like to add '0' before the numbers in the middle so that they are sorted as in

$ ls -v
pro2e_u01_txt_vocabulaire_1_campus.mp3
pro2e_u01_txt_vocabulaire_2_personnes.mp3
pro2e_u01_txt_vocabulaire_3_presentations.mp3
pro2e_u01_txt_vocabulaire_4_identifier.mp3
pro2e_u01_txt_vocabulaire_5_bonjouraurevoir.mp3
pro2e_u01_txt_vocabulaire_6_commentcava.mp3
pro2e_u01_txt_vocabulaire_7_expressionspolitesse.mp3
pro2e_u01_txt_vocabulaire_11_descriptiveadjectives.mp3
pro2e_u01_txt_vocabulaire_12_nationality.mp3

What I have so far is

$ for i in *.mp3; do echo ${i/_[0-9]_/_0¿_}; done
pro2e_u01_txt_vocabulaire_11_descriptiveadjectives.mp3
pro2e_u01_txt_vocabulaire_12_nationality.mp3
pro2e_u01_txt_vocabulaire_0¿_campus.mp3
pro2e_u01_txt_vocabulaire_0¿_personnes.mp3
pro2e_u01_txt_vocabulaire_0¿_presentations.mp3
pro2e_u01_txt_vocabulaire_0¿_identifier.mp3
pro2e_u01_txt_vocabulaire_0¿_bonjouraurevoir.mp3
pro2e_u01_txt_vocabulaire_0¿_commentcava.mp3
pro2e_u01_txt_vocabulaire_0¿_expressionspolitesse.mp3

I don't know what should be put in place of '¿' so that the number that matched [0-9] appears there instead.

Best Answer

Sometimes a specific solution is good enough; like in the current case where you can identify the patterns for the file subset to consider (e.g /_[0-9]_/) and add a leading zero depending on a uniquely identifying prefix (e.g. /re_/). Put all together that would be:

for f in *_[0-9]_*.mp3 ; do mv -i "${f}" "${f/re_/re_0}" ; done

For the pre-check you asked for you can add an echo in front of the mv.