简体   繁体   中英

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

I have been using a simple find command to search hundreds of html files and then replace some simple text within each file.

  1. To find and list files containing the search string.

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

Which gives me a simple list of files like.

    ./javascript_open_new_window_form.php
    ./excel_large_number_error.php
    ./linux_vi_string_substitution.php
    ./email_reformat.php
    ./online_email_reformat.php
  1. To search and replace the string I use.

     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 

So my question is... how can I combine the 2 commands so I do not manually have to copy and paste the file names each time.

Thanks for your help in advance.

您可以尝试这样:

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

Pipe it again to another xargs . Just make the second xargs use -n 1 to run the command one by one for each file in the input, rather then the default behavior. Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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