find matching text and replace next line

LinuxSed

Linux Problem Overview


I'm trying to find a line in a file and replace the next line with a specific value. I tried sed, but it seems to not like the \n. How else can this be done?

The file looks like this:

<key>ConnectionString</key>
<string>anything_could_be_here</string>

And I'd like to change it to this

<key>ConnectionString</key>
<string>changed_value</string>

Here's what I tried:

sed -i '' "s/<key>ConnectionString<\/key>\n<string><\/string>/<key>ConnectionString<\/key>\n<string>replaced_text<\/string>/g" /path/to/file

Linux Solutions


Solution 1 - Linux

One way: Sample file

$ cat file
Cygwin
Unix
Linux
Solaris
AIX

Using sed, replacing the next line after the pattern 'Unix' with 'hi':

$ sed '/Unix/{n;s/.*/hi/}' file
Cygwin
Unix
hi
Solaris
AIX

For your specific question:

$ sed '/<key>ConnectionString<\/key>/{n;s/<string>.*<\/string>/<string>NEW STRING<\/string>/}' your_file
<key>ConnectionString</key>
<string>NEW STRING</string>

Solution 2 - Linux

This might work for you (GNU sed):

sed '/<key>ConnectionString<\/key>/!b;n;c<string>changed_value</string>' file

!b negates the previous address (regexp) and breaks out of any processing, ending the sed commands, n prints the current line and then reads the next into the pattern space, c changes the current line to the string following the command.

Solution 3 - Linux

It works. Additionaly is interested to mention that if you write,

sed '/<key>ConnectionString<\/key>/!b;n;n;c<string>changed_value</string>' file

Note the two n's, it replaces after two lines and so forth.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbswinnertonView Question on Stackoverflow
Solution 1 - LinuxGuruView Answer on Stackoverflow
Solution 2 - LinuxpotongView Answer on Stackoverflow
Solution 3 - LinuxRubén ColominaView Answer on Stackoverflow