将文件名中包含特定字符串的目录中的所有文件复制到 Bash 中的不同目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14371039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:13:46  来源:igfitidea点击:

Copy all files in a directory with a particular string in the filename to different directory in Bash

filebashcopyfilenamesdirectory

提问by Suku

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.

我想将文件名中带有 'foo' 的文件复制到一个单独的目录中,以便它包含前三个文件而不是第四个文件。

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.

我环顾四周,但还没有想出办法做到这一点。该目录有大量文件,但只有 1% 左右需要复制。

Thanks

谢谢

回答by Suku

$ 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

回答by dough

Try this statement: cp *foo* /newdir

试试这个语句: cp *foo* /newdir

回答by mvds

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 -printgives you some indication of progress and can be left out. To simply list the files that are to be copied:

这不使用 shell 扩展,因此您不会尝试运行带有一百万个参数的命令。在-print为您提供了一些进展指示,并可以被排除在外。简单地列出要复制的文件:

find . -type f -depth 1 -name "*foo*"

回答by DreadPirateShawn

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.

这将确认要匹配的文件,然后您可以重新使用与 cp 命令相同的模式来执行副本。

回答by Johnsyweb

Use globbing:

使用通配符

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

This will output the copy command (or fail with bash: no match: *foo*).

这将输出复制命令(或失败bash: no match: *foo*)。

Remove the echowhen you've validated the output to actually copythe directory entries.

echo当您验证输出以实际复制目录条目时,请删除。