7

Let's say I want to rename all the files inside all the subfolders of a folder from foo.txt to bar.txt using zmv.

I've tried zmv '**/foo.txt' 'bar.txt' but this creates bar.txt in the root folder. How can I keep the files in their corresponding subfolder?

1 Answer 1

11

You need to reference the directory part in the target. You can do that by putting the wildcards in parentheses and using $1 to refer to the part matched by the parenthetical group. The ** wildcard is a little special and requires that the parentheses are around **/, no more, no less.

zmv '(**/)foo.txt' '${1}bar.txt'

You can use the -w flag to have each wildcard automatically made into a parenthetical group.

zmv -w '**/foo.txt' '${1}bar.txt'

Or you can use the -W flag and use wildcards in the replacement text — with this flag, the wildcards in the replacement text are turned into $1, $2, etc.

zmv -W '**/foo.txt' '**/bar.txt'

Alternatively, you can use $f to refer to the source path.

zmv '**/foo.txt' '$f:r.txt'
3
  • the zmv -W version is excellent and works exactly as expected.
    – Jay Dorsey
    Oct 17, 2019 at 15:22
  • Anyway for Zmv to create intermediate directory? For example, I’d like to move from src/**/foo.txt to dst/**/bar.txt, so the sub-directory under dst/ might be absent. My current workaround is an rsync before a zmv. Apr 11, 2022 at 7:10
  • 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.