Issue
I have a file where I want to find and replace a very specific line. I have provided a simplified file below which I'll call test.in. If I were to do this manually I would find "log 3" then I would find "old string" from that point and replace it with "new string". In practice the files are large with lots of information between LOG number and old string, but these are the unique identifiers.
*LOG 1
old string
old string
*LOG 2
old string
old string
old string
*LOG 3
old string [Want to replace this with "new string"]
*LOG 4
old string
old string
I thought about using the following:
grep -A 700 "*LOG 3" test.in | sed '0,/old string/{s/old string/new string/}'
But this doesn't work for me as I need to correct the entire file. I also came across the following on these pages:
awk '/old string/{count++;if(count==3){sub("old string","new string")}}1' test.in
However this also doesn't work as it assumes I know how many "old string" there are before I get to the one I need to replace - and in practice I don't as there are many different files.
I cannot simply find LOG 3 with a line space and old string and replace it that way, as there is a ton of different information between LOG 3 and old string.
Is there a simple way I can find something then search again from that new position, and then use sed/awk and save the entire file.
Many thanks :)
Solution
Simply 1 sed
line
sed '/^\*LOG 3/,/old string/s/old string/new string/' test.in
Translated:
From
*LOG 3
tonext line containing *old string*
, replaceold string
bynew string
Answered By - F. Hauri Answer Checked By - Robin (WPSolving Admin)