Sunday, April 28, 2024
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 2112  / 2 Years ago, sat, november 20, 2021, 1:23:41

I have a group of files that are named as follows:



048. banana.mkv
049. apple.mkv
050. mango.mkv
051. pear.mkv
052. grape.mkv


I need to rename those files with the following naming convention



01. banana.mkv
02. apple.mkv
03. mango.mkv
04. pear.mkv
05. grape.mkv


The problem is I have hundreds of files I need to rename and multiple groups that I need to start from 01 and increment. Generally I use rename to mass rename files. In this situation I have been using qvm to to change each filename. Surely there is an easier way.


More From » command-line

 Answers
6

Using the perl-based rename utility:



$ rename -n 's/^(d+)/sprintf "%02d", $1-47/e' *.mkv
rename(048. banana.mkv, 01. banana.mkv)
rename(049. apple.mkv, 02. apple.mkv)
rename(050. mango.mkv, 03. mango.mkv)
rename(051. pear.mkv, 04. pear.mkv)
rename(052. grape.mkv, 05. grape.mkv)


The trick here is the e modifier on the s/pattern/replacement/ substitution - which lets you evaluate the replacement string as a perl expression - including arithmetic $1-47 and padded formating via sprintf. Remove the -n when you are satisfied that it is doing the right thing.



If you only have a shell, then:



$ for f in *.mkv; do 
n="${f%%.*}"
printf -v newf '%02d.%s' "$((10#$n-47))" "${f#*.}"
echo mv -- "$f" "$newf"
done
mv -- 048. banana.mkv 01. banana.mkv
mv -- 049. apple.mkv 02. apple.mkv
mv -- 050. mango.mkv 03. mango.mkv
mv -- 051. pear.mkv 04. pear.mkv
mv -- 052. grape.mkv 05. grape.mkv


Remove the echo once you are happy that it's doing the right thing.






With zsh and zmv



% autoload zmv
% setopt expanded_glob
%
% zmv -n '(*[0-9])(*.mkv)' '${(l:2::0:)$(( $1-47 ))}$2'
mv -- '048. banana.mkv' '01. banana.mkv'
mv -- '049. apple.mkv' '02. apple.mkv'
mv -- '050. mango.mkv' '03. mango.mkv'
mv -- '051. pear.mkv' '04. pear.mkv'
mv -- '052. grape.mkv' '05. grape.mkv'


In this case, the number formating is done using the l (letter ell) expansion modifier - from man zshexpn:




   l:expr::string1::string2:
Pad the resulting words on the left. Each word will be trun‐
cated if required and placed in a field expr characters wide.



As with rename, remove the -n to actually change the names.


[#3249] Saturday, November 20, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tigehanc

Total Points: 162
Total Questions: 113
Total Answers: 122

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
tigehanc questions
Thu, Dec 22, 22, 01:47, 1 Year ago
Sat, Aug 28, 21, 03:26, 3 Years ago
Fri, Feb 10, 23, 05:50, 1 Year ago
;