Sed inline replaces sentence in text file AFTER matching

I am trying to replace the first instance of a sentence in a text file after a match is found. Note that the quotation marks are included in the search.

  • I am looking for the first instance : 'database' => 'localhost'
  • I am replacing the first instance with: 'database' => 'new_database'
  • I want to replace only after the line 'REPLACE_AFTER_THIS'

Currently, the first two points work for me:

 sed -i file -e "1s/'database' => 'localhost'/'database' => 'new_database'/;t" -e "1,/'database' => 'localhost'/s//'database' => 'new_database'/" file 

Input file

 'local config' ... 'data' 'more data' 'database' => 'localhost' 'even more data' 'REPLACE_AFTER_THIS' ... 'data' 'more data' 'even more data' 'database' => 'localhost' 'live config' 'database' => 'localhost' 

Expected output file (same file modified in line)

 'local config' ... 'data' 'more data' 'database' => 'localhost' 'even more data' 'REPLACE_AFTER_THIS' ... 'data' 'more data' 'even more data' 'database' => 'new_database' 'live config' 'database' => 'localhost' 

The above example shows how there is no expected data format, except for the string 'database' => 'localhost' , the first occurrence of which must be changed after 'REPLACE_AFTER_THIS' .

However, I cannot figure out how to do this only after finding a specific line. I tried using grep and a template to extract all the text after REPLACE_AFTER_THIS , but then connecting to sed instead of using the -i flag no longer makes any changes to the file.

How can I change the current working solution to enable the replacement of the first instance of the sentence after this line is found in the file?

+4
source share
2 answers

Try this with GNU sed:

 sed -i "/'REPLACE_AFTER_THIS'/,/'database' => 'localhost'/s/'database' => 'localhost'/'database' => 'new_database'/" file 
+2
source

You can use awk for this:

 temp=$(mktemp /tmp/temporary-file.XXXXXXXX) awk "/REPLACE_AFTER_THIS/{u=1} u && sub(/'database' => 'localhost'/, \"'database' => 'new_database'\") {u=0} 1" file > "$temp" 

Output:

 'local config' ... 'data' 'more data' 'database' => 'localhost' 'even more data' 'REPLACE_AFTER_THIS' ... 'data' 'more data' 'even more data' 'database' => 'new_database' 'live config' 'database' => 'localhost' 
+1
source

All Articles