2

I want to rename the following files 0 , 0.001 ,0.002 , 0.003 ... , 0.035

into 0 , 1 , 2 , 3 ... , 35

How can I do it?

3

bash solution (provided extglob shell option is enabled - see pattern matching manual)

for i in 0.* ; do mv "$i" "${i##0.*(0)}" ; done
  • ${i## delete longest match from beginning of i variable
  • 0. matches the character sequence 0.
  • *(0) means zero or more occurrences of 0

or this solution suggested by @Costas, which doesn't need the extglob option

for i in 0.* ; do mv "$i" "${i#${i%%[!0.]*}}" ; done
  • ${i%% delete longest match from end of i variable
  • * any character, zero or more times
  • [!0.] characters other than 0.
  • so, ${i%%[!0.]*} effectively deletes from first non 0 or . character till end. For ex: 35 gets deleted for 0.035, 1 for 0.001, str0.00456a for 0str0.00456a and entire string for str0.00456a
  • the remaining characters (ex: 0.0 for 0.035 and 0.00 for 0.001 gets passed to ${i# which then deletes these characters from beginning of variable, resulting in 35 for 0.035 and 1 for 0.001

Further reading: Parameter Expansion

  • 1
    Or ${i#${i%%[!0.]*}} if you have not extglob option – Costas Jul 18 '16 at 5:43
  • 1
    For pattern match it is not fully true explanation: * means any symbol(s) in any quantity (include nothing), %%[!0.] means *leftmost* symbol other than "0" and "." – Costas Jul 18 '16 at 6:55
  • @Costas, thanks for explanation.. I've updated the answer, can you see if it is okay? – Sundeep Jul 18 '16 at 7:56
  • Yes, it is OK now – Costas Jul 18 '16 at 9:53
  • Thank you very much , works perfectly but I have another problem. – Konstantinos Giannokostas Jul 18 '16 at 13:58
1

With rename (prename):

rename -n 's/^[^.]+\.0*([1-9]+)$/$1/' 0*

-n will do the dry-run, if you are satisfied with the changes to be made, do:

rename 's/^[^.]+\.0*([1-9]+)$/$1/' 0*

Example:

% rename -n 's/^[^.]+\.0*([1-9]+)$/$1/' 0*
0.001 renamed as 1
0.002 renamed as 2
0.003 renamed as 3
0.035 renamed as 35
  • or just rename -n 's/0\.0*//' 0* ? – Sundeep Jul 17 '16 at 12:01
  • @spasic We need to be sure that we have digits at last, OP has not clarified that otherwise your one is correct too.. – heemayl Jul 17 '16 at 12:02
  • oh ok :) .. from question, I feel OP has exactly those 36 files – Sundeep Jul 17 '16 at 12:05

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.