To copy everything except 2 files

Hi all,

I would want to copy everything in a particular directory. However would want to exclude 2 files:
DIMStemp01.dbf
DIMSts01.dbf

I tried to:
(1) ls files except these 2 files into abc.txt
(2) Read from abc.txt and start copying.

It works, however is there any easier way? Eg. directly copy those files [excluding these 2]?

Thanks.

Several ways. In ksh and bash you can use

cp !(foo|bar) /my/destination/dir

to exclude files named "foo" and "bar".

Otherwise, you can do something like this:

echo cp `/bin/ls -1 . |grep -v "^foo$" | grep -v "^bar$" ` /my/destination/dir

There are more elegant and faster ways, but I'm not sure about portability. Also, this will pick up directory names, but rm will not remove them. Finally, when you are sure it's what you want to do, remove the "echo".

If your directory is really large, you'll need to use "xargs":

 ls -1 |grep -v ^foo$ | grep -v ^bar$ |xargs -i sh -c "test -f {} && echo cp {} /my/destination/dir "

This last one actually takes care to only remove files, and not hardlinks, sockets, directories, etc. Remove the "echo" to actually execute the copy.

Finally, there's always find:

 find  . -maxdepth 1 -type f \! \( -name foo -o -name bar -o -name foo*bar \) -exec echo cp "{}" /my/destination/dir ";"

Once again, this only touches files. You can make it completely recurse all directories by removing "maxdepth". Again, remove the "echo" to actually do it.

instead of 2 greps, you could use both the patterns separated by a pipe character or a single egrep would do

Thanks for the reply.

There's an error when:
cp !(foo|bar) /my/destination/dir
root@rskcs3 # cp !(abc.txt|bcd.txt) /tmp/test1
syntax error: `(' unexpected

I'm using ksh, seems like not working.:frowning:

Shall try out the next following codes.

What is the ^bar$ --^ & $ for? I'm still quite new in scripting

^ - start of the pattern
$ - end of the pattern

^bar$ - starts with 'b' and ends with 'r' with in 'a' in between.
Literally, it should match the pattern 'bar'

Thanks for the explanation. Really appreciate it~;)

I had this dilemma also..
This worked like a charm. It's easy to understand as well. :smiley: