4

I'm using the Perl rename command line tool to search recursively through a directory to rename any directories as well as files it finds. The issue I'm running into is the rename command will rename a sub-directory of a file then attempt to rename the parent directory of the same file. This will fail because the sub-directory has been renamed resulting in a "No such file or directory"

Command:

rename -f 's/foo/bar/' **
rename -f 's/Foo/Bar/' **

For example, here is an original file that I would like to replace 'foo' with 'bar'

File:

/test/foo/com/test/foo/FooMain.java

Failure:

Can't rename /test/foo/com/test/foo/FooMain.java /test/bar/com/test/foo/FooMain.java: No such file or directory

Preferred File:

/test/bar/com/test/bar/BarMain.java

You can see from the error message that it's attempting to rename the parent directory but at that point the subdirectory has already been changed resulting in the file not found error. Is there parameters for the rename command that will fix this or do I need to go about this in a different way?

1
  • They are separate lines running in a bash script. Would it act differently if I had combined them like your example?
    – Bobbake4
    May 23, 2017 at 14:21

2 Answers 2

7

I would go about this in a different way - specifically, using a depth-first search in place of the shell globstar **

For example, using GNU find, given:

$ tree
.
└── dir
    ├── foo
    │   └── baz
    │       └── MainFoo.c
    └── Foo
        ├── baz
        └── MainFoo.c

5 directories, 2 files

then

find . -depth -iname '*foo*' -execdir rename -- 's/Foo/Bar/;s/foo/bar/' {} +

results in

$ tree
.
└── dir
    ├── bar
    │   └── baz
    │       └── MainBar.c
    └── Bar
        ├── baz
        └── MainBar.c

5 directories, 2 files
1
  • Depth first really is the way to go.
    – l0b0
    May 23, 2017 at 14:32
0

As noted earlier, you are asking about perl and showing the code in sh.

If you want use Perl 5

  • Module File::Find::Rule will help you find will help you find directories.
  • Perl rename will do the rest of the job.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .