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?

2 Answers 2

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

7
  • 1
    Or ${i#${i%%[!0.]*}} if you have not extglob option
    – Costas
    Commented Jul 18, 2016 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
    Commented Jul 18, 2016 at 6:55
  • @Costas, thanks for explanation.. I've updated the answer, can you see if it is okay?
    – Sundeep
    Commented Jul 18, 2016 at 7:56
  • Yes, it is OK now
    – Costas
    Commented Jul 18, 2016 at 9:53
  • Thank you very much , works perfectly but I have another problem.
    – gkk
    Commented Jul 18, 2016 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
3
  • or just rename -n 's/0\.0*//' 0* ?
    – Sundeep
    Commented Jul 17, 2016 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
    Commented Jul 17, 2016 at 12:02
  • oh ok :) .. from question, I feel OP has exactly those 36 files
    – Sundeep
    Commented Jul 17, 2016 at 12:05

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.