Search code examples
bashshellzsh

How to copy multiple files from many directories to corresponding directories with different names?


I have an apps folder. I need to copy all the .env.test files in each directory inside the apps folder to the corresponding .env file.

So for example if I have the following 2 directories insided the apps folder:

  • client
  • server

I need to copy

  • apps/client/.env.test to apps/client/.env
  • apps/server/.env.test to apps/server/.env

I can do that using a for loop like

for dir in apps/*/; do cp "${dir}.env.test" "${dir}.env"; done

But I was wondering if there's a simpler one-liner way maybe using find -exec cp or tee .


Solution

  • Using find:

    find . -type f -iname '.env.test' | while read p; do cp "$p" "${p%\.test}"; done
    

    This uses the bash % Parameter Expansion operator to remove the .test suffix from the path: "${p%\.test}"

    How do I remove the file suffix and path portion from a path string in Bash?


    Small local demo:

    $ tree -a
    .
    └── apps
        ├── client
        │   └── .env.test
        └── server
            └── .env.test
    
    4 directories, 2 files
    $
    $ find . -type f -iname '.env.test' | while read p; do cp "$p" "${p%\.test}"; done
    $
    $ tree -a
    .
    └── apps
        ├── client
        │   ├── .env
        │   └── .env.test
        └── server
            ├── .env
            └── .env.test
    
    4 directories, 4 files
    $