Search code examples
linuxshellrenamefile-rename

How do I rename lots of files changing the same filename element for each in Linux?


I'm trying to rename a load of files (I count over 200) that either have the company name in the filename, or in the text contents. I basically need to change any references to "company" to "newcompany", maintaining capitalisation where applicable (ie "Company becomes Newcompany", "company" becomes "newcompany"). I need to do this recursively.

Because the name could occur pretty much anywhere I've not been able to find example code anywhere that meets my requirements. It could be any of these examples, or more:

company.jpg
company.php
company.Class.php
company.Company.php
companysomething.jpg

Hopefully you get the idea. I not only need to do this with filenames, but also the contents of text files, such as HTML and PHP scripts. I'm presuming this would be a second command, but I'm not entirely sure what.

I've searched the codebase and found nearly 2000 mentions of the company name in nearly 300 files, so I don't fancy doing it manually.

Please help! :)


Solution

  • bash has powerful looping and substitution capabilities:

    for filename in `find /root/of/where/files/are -name *company*`; do
        mv $filename ${filename/company/newcompany}
    done
    for filename in `find /root/of/where/files/are -name *Company*`; do
        mv $filename ${filename/Company/Newcompany}
    done