找到匹配的文本并替换下一行

时间:2022-04-25 16:49:33

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?

我正在尝试在文件中找到一行,并用特定值替换下一行。我试过sed,但似乎不喜欢\ n。怎么办呢?

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

3 个解决方案

#1


26  

This might work for you (GNU sed):

这可能适合你(GNU sed):

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

#2


27  

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'替换为'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>

#3


4  

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

有用。 Additionaly有兴趣提一下,如果你写,

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.

注意两个n,它在两行之后替换,依此类推。

#1


26  

This might work for you (GNU sed):

这可能适合你(GNU sed):

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

#2


27  

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'替换为'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>

#3


4  

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

有用。 Additionaly有兴趣提一下,如果你写,

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.

注意两个n,它在两行之后替换,依此类推。