bash - shell 脚本: How to copy files with specific string from big corpus

标签 bash shell ack

我有一个小错误,不知道如何解决。我想从包含许多文件的大文件夹中复制文件,其中文件包含特定字符串。为此,我使用 grep、ack 或(在本例中)ag。当我在文件夹内时,它匹配没有问题,但是当我想通过以下脚本中的文件循环来执行此操作时,它不会循环匹配。这是我的脚本:

ag -l "${SEARCH_QUERY}" "${INPUT_DIR}" | while read -d $'\0' file; do
    echo "$file"
    cp "${file}" "${OUTPUT_DIR}/${file}"
done

SEARCH_QUERY 保存我想要在文件中查找的字符串,INPUT_DIR 是文件所在的文件夹,OUTPUT_DIR 是将找到的文件复制到的文件夹。 while do 有什么问题吗?

编辑: 感谢您的建议!我现在选择了这个,因为它还会查找子文件夹中的文件并保存包含所有文件的列表。

ag -l "${SEARCH_QUERY}" "${INPUT_DIR}" > "output_list.txt" 
while read file
do
    echo "${file##*/}"
    cp "${file}" "${OUTPUT_DIR}/${file##*/}"
done < "output_list.txt"

最佳答案

最好使用 find 命令来实现它,如下所示:

  find "${INPUT_DIR}" -name "*.*" | xargs grep -l "${SEARCH_QUERY}" > /tmp/file_list.txt

  while read file
  do
     echo "$file"
     cp "${file}" "${OUTPUT_DIR}/${file}"
  done < /tmp/file_list.txt
  rm /tmp/file_list.txt

或其他选项:

 grep -l "${SEARCH_QUERY}" "${INPUT_DIR}/*.*" > /tmp/file_list.txt 

 while read file
  do
     echo "$file"
     cp "${file}" "${OUTPUT_DIR}/${file}"
  done < /tmp/file_list.txt

  rm /tmp/file_list.txt

关于bash - shell 脚本: How to copy files with specific string from big corpus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51206689/

相关文章:

php - 剩下的SSH进程/作业?

python - Ubuntu nohup 关闭具体脚本

shell - 从 shell 启动时在 shell 中启动 Emacs

shell - 您将如何从 node.js 命令行脚本启动浏览器

linux - Unix,替换错误错误?

ack - 使用 ack 的 .ackrc 忽略目录

bash - 对标准输入中的文件列表执行 sed -i

在所有目录中搜索

linux - 删除空字符(Shell 脚本)

linux - 用数据填充 shell 脚本数组