Search code examples
linuxscpls

Exclude certain directories from ls and copy the remaining over to a shared path


I have a folder that contains sub-directories A,B,C and D. I need to copy directories A and D to another directory called 'copy' while excluding B and C(i.e. B and C doesn't get copied over). I was thinking about doing the following (in command-line pseudocode):

ls (selective ls on the source directory) | 
   scp -r {returned value from the ls} {target directory}

Is there a Linux command-line way to accomplish the above?


Solution

  • The simple answer is to only copy the directories you want:

    scp -r A D anotherhost:/path/to/target/directory
    

    This will do exactly what you've described in your example. A more general solution might look something like this:

    scp -r $(ls | egrep -v '^(B|C)$') anotherhost:/path/to/target/directory
    

    This command will work as long as the number of files in your source directory is not large. As the number of files goes up, you'll eventually run into a "command too long" error.

    Instead of using scp, you could use rsync, which has a variety of mechanisms for including/excluding files. For example:

    rsync --exclude='B/' --exclude='C/' . anotherhost:/path/to/target/directory