Home > Mobile >  Rename and copy specific files by preserving the relative path in ubuntu
Rename and copy specific files by preserving the relative path in ubuntu

Time:12-17

I have several .env.sample files in my project directory. And I want to copy them to the .env by preserving the relative path.

before

.env.sample
apps
  -- app
  -- .env.sample

after

.env.sample
.env
apps
  -- app
  -- .env.sample
  -- .env

I already tried something like this:

find . -name .env.sample -exec cp {} $(echo {} | awk -F.sample '{print $1}') \;

But it doesn't work. The second part of the cp command doesn't work as I expected. Maybe something about the escaping special character is needed.

Any command that could do the job would be appreciated. And I can learn something new about bash if someone can explain what the problem is in my approach.

CodePudding user response:

Something like:

find . -name .env.sample -execdir sh -c 'cp -- "$1" "${1%.*}"' _ {}  

CodePudding user response:

This would be more readable with a little loop:

for env_file in $(find . -name .env.sample); do
    # strip .sample from the file name
    new_file_name="${env_file/.sample}"
    # copy it
    cp "$env_file" "$new_file_name"
done

If you want to do it in a one-liner with awk, you could, execing a shell. The answers to these questions have more details on why your command didn't work, and how to fix it if you'd like to keep your original idea: one, two.

  • Related