Issue
I have text in my file and there are other blocks matching with:
build.gradle
:
...
staging {
buildConfigField 'String', 'FLAVOUR_NAME', '"appName"'
// buildConfigField 'String', 'HOST', '"https://abcd.com"'
buildConfigField 'String', 'HOST', '"https://example.com"'
buildConfigField 'String', 'MEDIA_HOST', '"https://example.com"'
buildConfigField 'String', 'APPHOSTURL', '"https://play.google.com/store/apps/details/"'
applicationId = "com.example.staging"
}
...
My objective is to find the next three lines to include the 'HOST' line (ignoring the commented ones) corresponding to the pattern:
staging {
I got it using:
sed -n "/staging {/{n;N;N;p;}" build.gradle
Output:
buildConfigField 'String', 'FLAVOUR_NAME', '"appName"'
// buildConfigField 'String', 'HOST', '"https://abcd.com"'
buildConfigField 'String', 'HOST', '"https://example.com"'
Further, I need to apply the pattern match from this output and replace the text in file then.
Another command that I got it using was:
sed -n "/staging {/{n;N;N;p;}" build.gradle | sed "/^\s\+\/\//! s/'HOST', .*$/'HOST', '\"https:\/\/test.com\"'/"
Output:
buildConfigField 'String', 'FLAVOUR_NAME', '"appName"'
// buildConfigField 'String', 'HOST', '"https://abcd.com"'
buildConfigField 'String', 'HOST', '"https://test.com"'
buildConfigField 'String', 'MEDIA_HOST', '"https://example.com"'
Everything is alright so far, but my problem is I don't know how to replace the changes in the existing file.
I need the final output (which should be replaced in the existing file) as:
...
staging {
buildConfigField 'String', 'FLAVOUR_NAME', '"appName"'
// buildConfigField 'String', 'HOST', '"https://abcd.com"'
buildConfigField 'String', 'HOST', '"https://test.com"'
buildConfigField 'String', 'MEDIA_HOST', '"https://example.com"'
buildConfigField 'String', 'APPHOSTURL', '"https://play.google.com/store/apps/details/"'
applicationId = "com.example.staging"
}
...
But sed -i
is not working after feeding the input from pipe output.
Kindly guide me the way with sed or awk or any other.
Solution
Here is a way to combine two sed
commands for this task, without folding any lines.
sed "/^staging {$/,/^}$/{
s/\(^\s*b.*'HOST', '\"\).*\(\"'\)/\1https:\/\/test.com\2/
}" file
The first range /^staging {$/,/^}$/
defines the area where the following substitution {s/...}
can happen. Note that if you have many {}
blocks , the substitution will be tested only inside staging{ }
blocks.
You could add -i
for inplace editing after you are done with testing.
Answered By - thanasisp Answer Checked By - David Goodson (WPSolving Volunteer)