Rename Multiple Files with Same Digits After Decimal

I have multiple files with names vort-0.01.txt, vort-0.02.txt, ...

vort-0.1.txt ... vort-0.2.txt ... etc.

I want to rename each files with two decimal points i.e. I want to change the name of vort-0.1.txt to vort-0.10.txt and keep vort-0.01.txt as it is.

How can I do that in using bash script?

Thank you for your help.

2

1 Answer

Using the perl-based rename command, then given

$ ls vort*.txt
vort-0.001.txt  vort-0.01.txt  vort-0.1.txt  vort-0.2.txt

then

rename -n 's/(\d+\.\d+)/sprintf "%.2f", $1/e' vort*.txt

will impose 2-digit precision everywhere, as

rename(vort-0.001.txt, vort-0.00.txt)
rename(vort-0.1.txt, vort-0.10.txt)
rename(vort-0.2.txt, vort-0.20.txt)

If you want to rename to a minimum precision i.e. only modify filenames that currently have single-digit precision, then

$ rename -n 's/(\d+\.\d)(?=\D)/sprintf "%.2f", $1/e' vort*.txt
rename(vort-0.1.txt, vort-0.10.txt)
rename(vort-0.2.txt, vort-0.20.txt)

Remove the -n once you are happy that it is doing the right thing.


To do the same thing using bash shell manipulations alone,

for f in vort-?.?.txt; do 
  base=${f%.txt}
  printf -v newname 'vort-%.2f.txt' "${base#vort-}"
  echo mv -- "$f" "$newname"
done

Here, remove the echo after testing.

1

Your Answer

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

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest