Appending (via rename?) `.bad` to files identified by `tests/test_.*`

Posted on

Problem :

What do I want?

Given the following directory structure:

.
├── bar.py
├── hap
│   ├── bla.py
│   └── tests
│       └── test_hap.py
└── hip
    ├── testimony.py
    └── tests
        ├── foo.py
        └── test_hip.py

I’d like to go to the following:

.
├── bar.py
├── hap
│   ├── bla.py
│   └── tests
│       └── test_hap.py.bad
└── hip
    ├── testimony.py
    └── tests
        ├── foo.py
        └── test_hip.py.bad

So, I want to append .bad to all files starting with test_ which are located in a tests directory.

What have I tried?

From the tips given in this thread, I tried the following:

shopt -s globstar
rename "s/tests/test_.*/tests/test_.*.bad/" **

But the .* in the new part of the substitution pattern s/old/new seems to be auto-escaped. How can I let the second .* be interpreted as a regular expression?

Furthermore, using test_.*.bad$ gives me the following:

Final $ should be $ or $name at (eval 1) line 1, within string 

Solution :

Find is great for things like this (note this may only work if your paths have no spaces).

find /directory/path -type f -name "test_*" -exec mv {} {}.bad ;

Find can filter on the directory tree to find what you want, then the exec argument to find allows you to substitute whatever was found into “{}”.

Leave a Reply

Your email address will not be published. Required fields are marked *