10

Open only files containing a specific string, and then replace them on the Linux...

 3 years ago
source link: https://www.codesd.com/item/open-only-files-containing-a-specific-string-and-then-replace-them-on-the-linux-command-line.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

advertisements

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.


You could try this :

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK