【问题标题】:Search and replace entire files搜索和替换整个文件
【发布时间】:2014-03-22 01:05:49
【问题描述】:

我见过很多在多个文件中用另一个字符串替换一个字符串的例子,但我想做的有点不同。可能要简单得多:)

找到与某个字符串匹配的所有文件,并将它们完全替换为新文件的内容。

我有一个有效的查找命令

find /home/*/public_html -name "index.php" -exec grep "version:1.23" '{}' \; -print 

这会找到我需要更新的所有文件。 现在如何用 /home/indexnew.txt 的内容替换它们的全部内容(我也可以将其命名为 /home/index.php)

我强调内容是因为我不想更改我正在更新的文件的名称或所有权。

【问题讨论】:

    标签: linux sed grep find exec


    【解决方案1】:
    find ... | while read filename; do cat static_file > "$filename"; done
    

    效率提示:使用grep -q -- 找到第一个匹配项时会立即返回“true”,而不必读取整个文件。

    【讨论】:

      【解决方案2】:

      如果您有一堆要替换的文件,并且您可以使用通配符获取它们的所有名称,您可以尝试将输出通过管道传输到 tee 命令:

      cat my_file | tee /home/*/update.txt
      

      这应该查看 /home 中的所有目录,并将 my_file 中的文本写入每个目录中的 update.txt。

      让我知道这是否有帮助或不是您想要的。

      【讨论】:

      • 如何将它与我的 find 命令结合使用?我需要批量替换 500 个文件。
      【解决方案3】:

      我不确定你的命令是否没有-l 然后打印它比直接在grep 中添加-l 到列表文件更好。

      find /home/*/public_html -name "index.php" -exec grep -l "version:1.23" '{}' \;  |xargs -i cp /home/index.php {}
      

      这里是选项-l详情

         -l, --files-with-matches
                Suppress  normal  output;  instead  print the name of each input
                file from which output would normally have  been  printed.   The
                scanning  will  stop  on  the  first match.  (-l is specified by
                POSIX.)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多