How to copy over all files from one directory to another excluding ones that start with a given string in a bash script

Viewed 56

I have a directory containing a large amount of files ~1gb. I need to copy over all of them except ones that start with "name" to a different directory. I tried using this: "ls src_folder | grep -v '^name' | xargs cp -t dest_folder" from this pervious question In Linux, how to copy all the files not starting with a given string?

I get the following error when trying to copy over test1.txt from src_folder which contains test1.txt and name.txt to dest_folder

cp: cannot stat `test1.txt': No such file or directory

My current work around is to copy over all of the files, then use find to delete the ones starting with "name" in the dest_folder. This works, but I imagine I could save some time by only copying over the files I really want. Any suggestions?

1 Answers

You can use the shell option extglob. This option extends the bash's pattern matching, so you can use more advanced expressions.

shopt -s extglob
cp src_folder/!(name*) dest_folder

For more info run nam bash and look for extglob.

Related