1

I have a folder structure

conf/
    widget1/
        env1.cfg
        env2.cfg
    widget2/
        env1.cfg
        env2.cfg
    widget3/
        env1.cfg
        env2.cfg
    widget4/
        env1.cfg
        env2.cfg
    ...

What I want to do is find all the files named env2.cfg, and create a copy of them in their directory named env3.cfg.

I've tried:

find -name env2.cfg -exec cp '{}' "env3.cfg" ";"

but that just created env3.cfg in the conf/ directory.

Any thoughts?

For clarification I'm doing this on Mac OSX, but ideally the same command should work on CentOS if possible.

2

Try

find . -name env2.cfg -execdir cp {} env3.cfg \;

By replacing exec to execdir. It will mean that your 'action' (cp) will take place inside the folder where the file (env2.cfg) have been found.

  • 1
    Does the Mac's find have the excellent -execdir? – roaima Apr 17 '15 at 16:32
  • Sure, it does :) – DiFS Apr 19 '15 at 22:34
2

Your example copies all env2.cfg files to the current working directory, which is ".". You need to give the file found a new name, including its directory. This one worked for me:

for file in $(find . -name env2.cfg); do backup=$(echo $file | sed 's/env2.cfg/env3.cfg/'); cp $file $backup; done

edit: Or the even more elegant way, so you don't have to bother with multiple commands:

for file in $(find . -name env2.cfg); do cp $file ${file/env2/env3}; done
1

Since it's a static structure you can directly address the filenames and let the shell copy them:

for f in conf/widget*/env2.cfg
do
    cp "${f}" "${f/env2/env3}"
done

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.