Search code examples
unixcommand-linerenamecshbatch-rename

Rename all subdirectories in csh shell


I'm using csh and I have a directory structure containing multiple sub-directories. I'm trying to rename all the directories and sub-directories but not the files inside these directories. So something like

From

topdir1
--dir11
--dir12
topdir2
--dir21
----dir211
--dir22

to

topdir1.test
--dir11.test
--dir12.test
topdir2.test
--dir21.test
----dir211.test
--dir22.test

I can list the directories with find . -maxdepth 3 -type d. I'm trying to use a foreach loop to rename them. So

foreach i (`find . -maxdepth 3 -type d`)
mv $i $i.test
end

But this doesn't work as once the top level directory is renamed, it cannot find the sub-directories, so it only renames the top level directories.

Any idea on how to go about this?

Thanks


Solution

  • How about reversing the find results so that the subdirectories are listed first?

    foreach i (`find ./* -maxdepth 3 -type d | sort -r`)
    mv $i $i.test
    end
    

    Sort will output the longest directory names last, using the -r (reverse) flag changes it so that the lowest directories will be listed first, and be renamed before their parent directories do.