Copy all files to a directory with a specific line in the file name in another directory in Bash

For example, a directory may contain files

12_foo9.dat 34foo32.txt 24foobar.png 997_bar.txt 

and I would like to copy the files named "foo" in the file names to a separate directory so that it contains these first three files, but not the fourth.

I looked around, but did not understand how to do this. The directory has a very large number of files, but only 1% or so of what I need to copy.

thanks

+6
source share
5 answers
 $ mkdir NEWDIR $ touch foo_file file_foo file_foo_file $ ls NEWDIR file_foo file_foo_file foo_file $ cp -v *foo NEWDIR/ file_foo -> NEWDIR/file_foo $ cp -v foo* NEWDIR/ foo_file -> NEWDIR/foo_file $ cp -v *foo* NEWDIR/ file_foo -> NEWDIR/file_foo file_foo_file -> NEWDIR/file_foo_file foo_file -> NEWDIR/foo_file $ ls NEWDIR/ file_foo file_foo_file foo_file 
+8
source

Try the following statement: cp *foo* /newdir

+4
source

If you are really worried about the number of files (for example, running in millions), you can use:

 find . -type f -depth 1 -name "*foo*" -exec cp {} /otherdir \; -print 

This does not use a shell extension, so you will not try to run a command with a million arguments. -print gives you some indication of progress and may be omitted. To simply copy the files you need to copy:

 find . -type f -depth 1 -name "*foo*" 
+2
source

Use globbing :

 shopt -s failglob echo cp *foo* /path/to/separate 

This will produce a copy command (or crash with bash: no match: *foo* ).

Remove echo when you checked the output to actually copy the entries in the directory.

0
source
 cp *foo* /path/to/separate_directory 

If you want to first check the files to be included, use:

 ls *foo* 

This will confirm the matching files, then you can reuse the same template with the cp command to execute the copy.

0
source

All Articles