Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

linux - find matching text and replace next line

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 . 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>
<string></string>/<key>ConnectionString</key>
<string>replaced_text</string>/g" /path/to/file
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...