【问题标题】:How to I search for a text string and copy those files to another directory如何搜索文本字符串并将这些文件复制到另一个目录
【发布时间】:2013-07-04 04:09:33
【问题描述】:

我需要在一些文件中找到一个文本字符串。这会给我一个清单:

find . -type f -print0 | xargs -0 grep -il "google"

然后我需要将这些文件复制到一个文件夹并重命名它们。所以我想我需要再次将它们传递给这样的东西

| xargs -0 -n1  -I '{}' cp '{}' ../testTarget/{}_RECOVERED

唉:

find . -type f -print0 | xargs -0 grep -il "google" |
xargs -0 -n1  -I '{}' cp '{}' ../testTarget/{}_RECOVERED

结果:cp: {}: No such file or directory

请指教

  • 文件名中包含空格和逗号 (Dovecot)

【问题讨论】:

标签: unix command-line find xargs cp


【解决方案1】:
find . -type f -print0 | xargs -0 grep -lh "google" | xargs -I % cp % ../testTarget/%_RECOVERED

find SOURCE/ -type f -print0 | xargs -0 grep -lh "SEARCH_STRING" | xargs -I % cp % TARGET_DIR/%_RECOVERED

【讨论】:

    【解决方案2】:
    for i in `ls -1tr`
    {
    SEARCH_STRING_LINE_NO=`grep -n SEARCH_STRING i | cut -d: -f1`;
    if [ SEARCH_STRING_LINE_NO > 0 ] then
    cp i folder_path_where_u_want_to_copy
    fi
    }
    

    将 SEARCH_STRING 替换为您要查找的文本字符串。

    将 folder_path_where_u_want_to_copy 替换为您要移动包含 SEARCH_STRING 的文件的文件夹路径

    这应该将包含 SEARCH_STRING 的文件复制到文件夹 folder_path_where_u_want_to_copy

    我没有测试过这段代码,因为我现在没有unix盒子,但至少它应该给你一个接近的想法

    【讨论】:

    • 问题似乎是它不处理文件名中的空格。这就是我调整脚本的方式。 '代码' #! /bin/bash for i in ls -1tr do SEARCH_STRING_LINE_NO=grep -n "google" $i | cut -d: -f1;如果 [ SEARCH_STRING_LINE_NO > 0 ] 然后 cp $i "testTarget/" fi 完成
    【解决方案3】:

    以下命令会将grep 用于patterncopy 的文件放到您想要的位置。

    find /path/to/search -type f -exec grep -q "pattern" '{}' ';' -exec cp '{}' /path/to/copy ';'
    

    复制完文件后,您可以使用rename 命令相应地重命名它们。

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 2018-10-08
      • 2013-06-25
      • 1970-01-01
      • 2021-04-18
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多