vividos vividos - 1 year ago 142
Linux Question

How to rename all folders and files to lowercase on Linux?

I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ sourcecode, but that shouldn't matter). Bonus points for ignoring CVS and SVN control files/folders. Preferred way would be a shell script, since shell should be available at any Linux box.

There were some valid arguments about details of the file renaming.

  1. I think files with same lowercase names should be overwritten, it's the user's problem. When checked out on a case-ignoring file system would overwrite the first one with the latter, too.

  2. I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code).

  3. The script would be needed to run a build on a Linux system, so I think changes to CVS or SVN control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.

Answer Source

A concise version using "rename" command.

find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \;

This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. "A/A" into "a/a").

Or, a more verbose version without using "rename".

for SRC in `find my_root_dir -depth`
    DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'`
    if [ "${SRC}" != "${DST}" ]
        [ ! -e "${DST}" ] && mv -T "${SRC}" "${DST}" || echo "${SRC} was not renamed"

P. S.

The latter allows more flexibility with move command (e. g. "svn mv").

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download