Search code examples
bashrenamesubdirectory

Single line bash command to rename all files with name A to name B


Given the file and folder structure:

test
├── a
│   └── hans.x
├── b
│   └── hans.x
└── c
    └── hans.x

I would like to use a single line bash command to rename all files "hans.x" to "peter.x".

Desired Result:

test
├── a
│   └── peter.x
├── b
│   └── peter.x
└── c
    └── peter.x

I have looked at many solutions on SO and found lots of solutions that show how to rename the file "peter.x" to "peter.x_somethingmore", but never the above scenario.

I have tried the following:

find . -type f -name 'hans.x' -print0 | xargs --null -I{} mv {} "$(dirname "{}")"peter.x

But unfortunately, that results in the following execution:

mv ./test/a/hans.x .peter.x
mv ./test/c/hans.x .peter.x
mv ./test/b/hans.x .peter.x

Solution

  • $(...) is expanded before xargs is executed. You want to run it all inside a subshell created when parsing the line:

       ... | xargs -0n1 sh -c 'mv "$1" "$(dirname "$1")"/hans.y' _