2

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?

johnk_21
  • 23
  • 4
  • [This answer](https://stackoverflow.com/a/4670152/9952196) from your linked question is the best approach. – Shawn Jul 09 '21 at 16:40
  • @Shawn This worked, don't know how I missed that. Thanks. – johnk_21 Jul 09 '21 at 17:31
  • FYI, if you have a **large** number of files in the directory, `/bin/ls` might return to many arguments. In such a case, use `find`. – Nic3500 Jul 10 '21 at 02:21

1 Answers1

2

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.

Carlos Marx
  • 496
  • 1
  • 6
  • 13