1

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.

  • 1
    you want to rename files with regular expressions. See : https://askubuntu.com/questions/175281/rename-files-by-regexp-in-command-line AND https://stackoverflow.com/questions/11809666/rename-files-using-regular-expression-in-linux – cmak.fr Nov 12 '20 at 07:50
  • mmv is well suited for this kind of renaming –  Nov 12 '20 at 09:38

1 Answers1

2

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.

steeldriver
  • 136,215
  • 21
  • 243
  • 336
  • Thank you for your answer. The rename command solve my purpose. However, when I use the bash shell manipulation using for loop it shows "bash: printf: ?.?: invalid number". – Hiranya Deka Nov 20 '20 at 02:30