繁体   English   中英

仅打开包含特定字符串的文件,然后在Linux命令行上进行替换

[英]Open only files containing a specific string and then replace on Linux command line

我一直在使用简单的find命令来搜索数百个html文件,然后在每个文件中替换一些简单的文本。

  1. 查找并列出包含搜索字符串的文件。

     find . -iname '*php' | xargs grep 'search-string' -sl 

这给了我一个简单的文件列表。

    ./javascript_open_new_window_form.php
    ./excel_large_number_error.php
    ./linux_vi_string_substitution.php
    ./email_reformat.php
    ./online_email_reformat.php
  1. 搜索并替换我使用的字符串。

     sed -i 's/search-string/replace-string/' ./javascript_open_new_window_form.php sed -i 's/search-string/replace-string/' ./excel_large_number_error.php sed -i 's/search-string/replace-string/' ./linux_vi_string_substitution.php sed -i 's/search-string/replace-string/' ./email_reformat.php sed -i 's/search-string/replace-string/' ./online_email_reformat.php 

所以我的问题是...如何合并这两个命令,所以我不必每次都手动复制和粘贴文件名。

感谢您的帮助。

您可以尝试这样:

find . -iname '*php' | xargs grep 'search-string' -sl | while read x; do echo $x; sed -i 's/search-string/replace-string/' $x; done

再次将其传送到另一个xargs 只需让第二个xargs使用-n 1来为输入中的每个文件一个接一个地运行命令,而不是默认行为。 像这样:

find . -iname '*php' | xargs grep 'search-string' -sl | xargs -n 1 sed -i 's/search-string/replace-string/'

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM