Search code examples
linuxbashshellfindmv

Find and move files to appropriate directories using shell script


I have below setup and I want to find and move files.

I have files /home/backup/abc/123.wav and /home/backup/xyz/456.wav. Same directories exist at /usr/src/abc and /usr/src/xyz which does not have any files.

I want to find .wav files from home_dir and move them to particular dest_dir.

So 123.wav should move to /usr/src/abc and 456.wav should move to /usr/src/xyz. I am using below command for that.

home_dir=/home/backup/
dest_dir=/usr/src/
cd $home_dir && find . -iname "*.wav" -exec mv {} $dest_dir \;

But all the .wav files(123.wav and 456.wav) moved to /usr/src and not to its respective directories(/usr/src/abc and /usr/src/xyz).

Is it possible to achieve what I want ? Please suggest.


Solution

  • Use cp --parents option with find to create parent directories of each file being copied:

    home_dir=/home/backup/
    dest_dir=/usr/src/
    cd "$home_dir"
    
    find . -iname "*.wav" -exec cp --parents {} "$dest_dir" \; -delete