You can use find
and the perl version of rename
to do this. For example:
First, I'll set up a testing environment:
$ mkdir /tmp/goldenburrito
$ cd /tmp/goldenburrito
$ mkdir -p 'dir1/001/11-20-2001-RT SIMULATION-5797' \
'dir1/002/11-20-2001-RT SIMULATION-30560' \
'dir1/003/08-24-1998-RT SIMULATION-72882'
$ mkdir dir2
Then rename the "RT SIMULATION" sub-directories:
$ find dir1 -mindepth 2 -maxdepth 2 \
-type d -name '*RT SIMULATION*' -print0 |
rename -0 -n 's:(/\d{3})/.*:$1:; s/^dir1/dir2/'
rename(dir1/003/08-24-1998-RT SIMULATION-72882, dir2/003)
rename(dir1/002/11-20-2001-RT SIMULATION-30560, dir2/002)
rename(dir1/001/11-20-2001-RT SIMULATION-5797, dir2/001)
The -mindepth 2
and -maxdepth 2
options used with find
restrict the matches to only the second level directories beneath dir1
. The NUL-separated output from find
is piped into the rename
script (which can take file & dir names as command-line args or from stdin).
For each matching directory name, the rename
script first removes everything after the 3-digit directory name, then it changes "dir1" at the start of the directory name to "dir2".
Note that rename
's -n
option makes it a dry run, so it will only show what it would do without actually renaming any directories. Remove the -n
, or replace it with -v
for verbose output, when you've confirmed that it does what you want.
Also note: perl rename
may be known as file-rename
, perl-rename
, prename
, or just rename
, depending on distro and/or how it was installed. On Debian, for example, it is called rename
and is in the rename
package (so, apt-get install rename
).
It is not to be confused with the rename
utility from util-linux
which has completely different and incompatible capabilities and command-line options.
You can tell which version you have installed by running rename -V
(if it mentions perl
or File::Rename
, it's the perl version).
Perl rename allows you to use any arbitrarily complex perl code to rename files, but is most often used to do simple sed-like s/search/replace/
operations on filenames.