简体   繁体   English

Bash:查找包含特定字符串的文件并将它们复制到文件夹中

[英]Bash: Find files containing a certain string and copy them into a folder

What I want: In a bash script: Find all files in current directory that contain a certain string "teststring" and cop them into a subfolder "./testfolder"我想要什么:在 bash 脚本中:在当前目录中查找包含某个字符串“teststring”的所有文件并将它们复制到子文件夹“./testfolder”中

Found this to find the filenames which im looking for找到这个以找到我正在寻找的文件名

find .找 。 -type f -print0 | -type f -print0 | xargs -0 grep -l "teststring" xargs -0 grep -l "teststring"

..and this to copy found files to another folder (here selecting by strings in filename): ..并将找到的文件复制到另一个文件夹(此处按文件名中的字符串选择):

find .找 。 -type f -iname " stringinfilename " -exec cp {} ./testfolder/ \\;型的F -iname “stringinfilename” -exec CP {} ./testfolder/ \\;

Whats the best way to combine both commands to achieve what I described at the top?结合这两个命令以实现我在顶部描述的内容的最佳方法是什么?

Just let find do both:只需让 find 两者都做:

find . -name subdir -prune -o -type f -exec \
    grep -q teststring "{}" \; -exec cp "{}" subdir \;  

Note that things like this are much easier if you don't try to add to the directory you're working in. In other words, write to a sibling dir instead of writing to a subdirectory.请注意,如果您不尝试添加到您正在工作的目录中,那么像这样的事情会容易得多。换句话说,写入同级目录而不是写入子目录。 If you want to wind up with the data in a subdir, mv it when you're done.如果您想在子目录中结束数据,请在完成mvmv That way, you don't have to worry about the prune (ie, you don't have to worry about find descending into the subdir and attempting to duplicate the work).这样,您就不必担心prune (即,您不必担心 find 下降到子目录并尝试复制工作)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何查找某些文件并将其复制到文件夹中? - How to find certain files and copy them in a folder? 使用 Linux 查找包含特定字符串的文件并复制到目录 - Find Files Containing Certain String and Copy To Directory Using Linux 使用bash,如何查找所有包含特定字符串的文件并将其替换为现有文件? - Using bash, how do I find all files containing a specific string and replace them with an existing file? 在目录中的文件中找到字符串,然后将其复制 - find string inside files in a dir then copy them 如何在* NIX服务器上查找包含特定字符串的所有文件 - How to find all files on a *NIX server containing a certain string 我可以在 bash 中使用“cp”来查看文件和文件夹,并在更改后将它们复制到另一个文件夹中吗? - Can I use `cp` in bash to watch files and folders and upon changes, copy them other to another folder? Bash脚本在列表中查找文件,将其复制到dest,未找到打印文件 - Bash script to find files in a list, copy them to dest, print files not found 查找文件的模式,使用该模式创建一个文件夹,然后将文件复制到该文件夹​​中-Bash脚本 - Find pattern of the file, create a folder with that pattern and copy the files to that folder - Bash script 按名称查找文件夹然后复制文件 - Find folder by name then copy files “查找”文件中包含指定范围内的整数(以bash表示) - 'find' files containing an integer in a specified range (in bash)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM