-1

The order of the files is determined by a number that can be embedded in the filename, but sometimes in the beginning of the name e.g. file1.txt file2.txt file3.txt file10.txt file11.txt etc.. or 1.txt 2.txt 10.txt etc..

The renaming should result in names like... file01.txt file02.txt file03.txt file10.txt etc...

It is important that file1.txt will be file01.txt and not file10.txt to be file01.txt.

I think the filenames have to be formatted before renaming. I have no idea of how to do that on the command line, maybe it must be done by a script but I hope not.

The command should be given the number of digits we should have in the final name. If its possible to use a formatting string we also could give the position where we have the number(s).

larand
  • 773
  • 1
  • 9
  • 26

1 Answers1

2

Using the perl rename utility:

rename -n 's/\d+/sprintf("%02d", $&)/e' *.txt

Result would be:

$ ls
file10.txt  file1.txt  file2.txt  file3.txt

$ rename -n 's/\d+/sprintf("%02d", $&)/e' *.txt
rename(file1.txt, file01.txt)
rename(file2.txt, file02.txt)
rename(file3.txt, file03.txt)

If that looks good, remove the -n dry-run flag.

Note that the format string to sprintf determines the "width" of the zero-padding, so if you were dealing with filenames that get into the triple digits, you'd want to change that to "%03d", etc..

$ ls
file100.txt  file10.txt  file1.txt  file2.txt  file3.txt

$ rename -n 's/\d+/sprintf("%03d", $&)/e' *.txt
rename(file10.txt, file010.txt)
rename(file1.txt, file001.txt)
rename(file2.txt, file002.txt)
rename(file3.txt, file003.txt)
cody
  • 11,045
  • 3
  • 21
  • 36
  • This works whatever the number position in the filename. – Yoric Jan 20 '19 at 15:26
  • Ok, looks good at first but in the directory I have 13 files numbered from 1 to 13 but I just get the first 9 files renamed. I can't see where this limit is set? Of course, how stupid of me, as the result is 2 digits there's no need for renaming. – larand Jan 20 '19 at 15:32
  • @larand That's because the files with 10-13 need no modification, yes? You wouldn't zero-pad those. – cody Jan 20 '19 at 15:32
  • Yes, that's correct. I was just prepared to see all files processed as it have been in all other examples I tried. Thank's a lot! – larand Jan 20 '19 at 15:36