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?
Jimbo source share