Linux 找到匹配的文本并替换下一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18620153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
find matching text and replace next line
提问by bswinnerton
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
采纳答案by potong
This might work for you (GNU sed):
这可能对你有用(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.
!b
否定前一个地址 (regexp) 并中断任何处理,结束 sed 命令,n
打印当前行,然后将下一行读入模式空间,c
将当前行更改为命令后面的字符串。
回答by Guru
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>
回答by Rubén Colomina
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.
注意两个 n,它在两行之后替换,依此类推。