1

I have a list of files like the following:

pairs10_10.mp3
pairs10_11.mp3
pairs10_12.mp3
pairs10_13.mp3
pairs10_14.mp3
pairs10_15.mp3
pairs10_16.mp3
pairs10_17.mp3
pairs10_18.mp3
pairs10_19.mp3
pairs10_1.mp3
pairs10_2.mp3
pairs10_3.mp3
pairs10_4.mp3
pairs10_5.mp3
pairs10_6.mp3
pairs10_7.mp3
pairs10_8.mp3
pairs10_9.mp3
pairs1_10.mp3

I would like to get something like the following so that when they are later sorted they would be in the correct order:

pairs10_10.mp3
pairs10_11.mp3
pairs10_12.mp3
pairs10_13.mp3
pairs10_14.mp3
pairs10_15.mp3
pairs10_16.mp3
pairs10_17.mp3
pairs10_18.mp3
pairs10_19.mp3
pairs10_01.mp3
pairs10_02.mp3
pairs10_03.mp3
pairs10_04.mp3
pairs10_05.mp3
pairs10_06.mp3
pairs10_07.mp3
pairs10_08.mp3
pairs10_09.mp3
pairs01_10.mp3

I just learned about the rename command but I don't know how to do this type of rename.

5
  • 1
    Don't rename them use the sort command. Use the -n option.
    – eyoung100
    Oct 3 '14 at 3:18
  • @eyoung100 That's a good idea too.
    – Curious
    Oct 3 '14 at 3:38
  • Using bash: for f in $(find . -name "pairs?_10.mp3"); do mv "$f" "${f%?_10.mp3}0${f#./pairs}" ; done;
    – user17530
    Oct 3 '14 at 3:41
  • This is just a partial list. The pattern is "pairs" + (1 or 2 digit number) + "_" + (1 or 2 digit number) + ".mp3"
    – Curious
    Oct 3 '14 at 3:53
  • You have not said anything about how to choose 0 or 1 or 2 when renaming. You then need to add these rules in your question
    – user17530
    Oct 3 '14 at 3:59
2

With the Perl rename command:

rename 's/([0-9]+)_([0-9]+)/sprintf("%02d_%02d",$1,$2)/e' *.mp3

The e modifier to the s substitution operator means that the replacement is a Perl expression rather than an interpolated string. The format %02d for the function sprintf formats an integer with exactly two digits, adding leading zeroes as necessary.


Alternatively, use zsh and its numeric_glob_sort option. However that only applies when zsh is doing the globbing (as in play pairs*.mp3).

1

POSIX:

for f in *;do x=${f#pairs};y=${f#*_};mv $f pairs_$(printf %02d_%02d ${x%_*} ${y%.mp3}).mp3;done

zsh:

autoload zmv;zmv 'pairs(*)_(*).mp3' 'pairs${(l:2::0:)1}_${(l:2::0:)2}.mp3'

0

I ended up using a multi-step process with the rename command. It could probably be simplified:

rename 's/(pairs)([0-9])_/$1Z$2_/' *.mp3
rename 's/(_)([0-9])\./$1Z$2\./' *.mp3
rename 's/Z/0/' *.mp3
rename 's/Z/0/' *.mp3

(The $1 and $2 refer to the parentheses in the first part)

("Z" is just a place holder because "0" gets mixed up with "$1")

idea from https://unix.stackexchange.com/a/147912/86521

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.