Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find matching text and replace next line

Tags:

linux

sed

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 
like image 940
bswinnerton Avatar asked Sep 04 '13 17:09

bswinnerton


People also ask

How do you replace some text pattern with another text pattern in a file?

`sed` command is one of the ways to do replacement task. This command can be used to replace text in a string or a file by using a different pattern.

How do you use sed to match word and perform find and replace?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do you go to the next line after grep?

Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.


2 Answers

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> 
like image 175
Guru Avatar answered Sep 22 '22 15:09

Guru


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.

like image 29
potong Avatar answered Sep 20 '22 15:09

potong