Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a directory consists of several files. Files name are as follows;

0102920.05o
0203920.05o
0304920.05o
....

I need to add "0" for all files after the first 4 numbers like;

01020920.05o
02030920.05o
03040920.05o

Is there a way to do it with bash or perl?

share|improve this question
up vote 5 down vote accepted

Use this command

rename -n -v 's/(.{4})(.*)/${1}0${2}/' *

See if the result is what you want, remove -n and -v options.

Explanation:

take this simple command:

rename 's/pattern/result/' filename(s)

Pattern can be regex. So, we can take different part of the text (which is the filename). If you don't understand it, google for regex.

So in the command I suggest, in pattern, it divide the filename into two parts: first part which is first four characters and the second part is the rest.

Now in the result part, we paste first part, add one 0 and then add the second part. As simple as this.

If you can make proper regex, you can easily do bulk rename.

share|improve this answer
1  
Or also simply rename -n -v 's/.{4}/${&}0/' * – kos Mar 24 at 15:14
    
@kos Nice one. Thanks for sharing – Mostafa Ahangarha Mar 24 at 15:17
    
thank you very much for the explanation @Mostafa – deepblue_86 Mar 24 at 15:22
    
Most welcome. I hope it could help you to understand and use it next time yourself. Bests – Mostafa Ahangarha Mar 24 at 15:24

something like that can do the trick in bash for all files in current directory

for filename in *;do
    mv "$filename" "${filename:0:4}0${filename:5:11}"
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.