Copy nearly every file with bash

I found an interesting trick in bash today that may help a few other folks as well. Occasionally I find that need to copy almost every file in a directory, except for one or two. Usually I'd copy everything and then delete the stragglers I didn't want from the destination directory. There had to be a better way, but as I said I'm lazy. Turns out I found the better way today.

[jperrin@ferrata ~]$ cp -r !(file_to_ignore)  /destination/

This little trick gets a bit better. Bash is slick enough to understand 'or' in this context. So I can also ignore multiple files if I need to

[jperrin@ferrata ~]$ cp -r !(file_to_ignore| this-one-too)  /destination/

Hopefully someone else finds this helpful as well.


fcoromo said...

rsync's --exclude parameter should get similar results too.

abdussamad said...

Doesn't work on my openSUSE system. I get the following error:

bash: !: event not found

Jim Perrin said...

You're probably getting these because of some bash options set by default on opensuse. Have a look at the output of 'shopt' and see if extglob is on. If not, that's why.

abdussamad said...

Thanks Jim. It works now. For anyone else wondering about this you have to do a:

shopt -s extglob

to enable extended pattern matching and then you can do a cp !(whatever) . and it will work.


Post a Comment

Copyright © Bit Integrity