Thibauld - Imagination and Execution -

24Feb/091

How to recursively rename directories using a regexp

RT @thibauld How to recursively rename directories using a regexp

Just a very quick post because I just figured out a command to recursively rename directories. As it is the kind of useful commands you don't want to loose and as it might be of interest for others, I thought I would share it here. So here is the command:
find -type d -name '*-test' | while read A; do OLD=$(basename $A); NEW=$(echo $OLD | sed s/-test//); mv $A $(dirname $A)/$NEW; done;

In this example, the command recursively finds all directories named <anything>-test and renames them <anything> (removing the trailing '-test'). I hope it will be useful for some of you...

Comments (1) Trackbacks (0)
  1. I do prefer using Perl for this kind of small task:

    find . -type d -name “*-test” | sort -r | perl -ne ‘chomp; $on=$_; $nn=$_; $nn =~ s/-test$//; print “mv $on $nn\n”‘ | bash

    The advantage is that you can prepare the commands to execute and once it’s OK, you add the ” | bash” at the end of the command.

    Warning: don’t forget to add the “sort -r” because if you have nested “*-test” directories, it will first move the nested directories.

    thibs.orig
    thibs.orig/b
    thibs.orig/b/ba
    thibs.orig/b/ba/baa
    thibs.orig/b/ba/bab-test
    thibs.orig/a-test
    thibs.orig/a-test/aa
    thibs.orig/a-test/aa/aaa-test

    thibs
    thibs/a
    thibs/a/aa
    thibs/a/aa/aaa
    thibs/b
    thibs/b/ba
    thibs/b/ba/baa
    thibs/b/ba/bab


Leave a comment


No trackbacks yet.