4

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?

5

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.

  • 1
    Or also simply rename -n -v 's/.{4}/${&}0/' * – kos Mar 24 '16 at 15:14
  • Most welcome. I hope it could help you to understand and use it next time yourself. Bests – Mostafa Ahangarha Mar 24 '16 at 15:24
3

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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