Copy all files in a directory with a particular string in the filename to different directory in Bash
Solution 1
$ 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
Solution 2
Try this statement: cp *foo* /newdir
Solution 3
cp *foo* /path/to/separate_directory
If you want to validate the files that will be included first, the use:
ls *foo*
This will confirm the files to be matched, then you can re-use the same pattern with the cp command to execute the copy.
Solution 4
If you are really concerned about the number of files (e.g. running in the millions) you could use:
find . -type f -depth 1 -name "*foo*" -exec cp {} /otherdir \; -print
This doesn't use shell expansion, so you will not try to run a command with a million arguments. The -print
gives you some indication of progress and can be left out. To simply list the files that are to be copied:
find . -type f -depth 1 -name "*foo*"
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
For example, a directory could contain the files
12_foo9.dat 34foo32.txt 24foobar.png 997_bar.txt
and I would like to copy the files with 'foo' in the file names to a separate directory so that it would contain those first three files but not the fourth.
I've looked around but haven't figured out a way to do this. The directory has a very large number of files, but only 1% or so that I need to copy.
Thanks
-
DreadPirateShawn over 11 yearsWhat benefit does the "echo" provide? It doesn't clarify which files are going to be included. If you want that, you'd want "ls foo" to confirm the files that will be matched, then "cp foo /target" to copy the same. Actually, I think I'll add that suggestion to my answer...
-
johnsyweb over 11 years@DreadPirateShawn: Thanks for the comment. I've updated my answer (tested with Bash v4.2.37).
-
Admin over 11 yearsThanks, that's so simple, sorry for asking something so obvious!
-
dough over 11 yearsNP - I don't want to hustle for rep but feel free to accept this answer :-)
-
aerin about 6 yearswhat does -v do?
-
Matt over 5 years
-v
is the "verbose" flag, causing it to output exactly which files are being moved