Sed: replace multiline
I am trying to do a multi-line replacement using sed on OSX (zsh). My input file (Unity Asset file) looks like this:
...
displaySetting: 0
applicationIdentifier:
Android: com.appid.name
Standalone: com.appid.name
Tizen: com.appid.name
iOS: com.appid.name
tvOS: com.appid.name
buildNumber:
iOS: 190
someOtherID: 190
moreIDsOverHere: 978987
...
I want to replace
buildNumber:
iOS: 190
from
buildNumber:
iOS: myBuildNumber
using the following command:
sed "N;s/^\\(.*buildNumber:.*.*$^.*iOS: \\)[0-9]*.*$/\\1myBuildNumber/;P;D" file.asset
This works except it also deletes the last line. I suspect it has something to do with my use of the stencil buffer, but I can't seem to find a solution.
Help would be greatly appreciated!
source to share
You don't need to use hold here. Try the following:
sed "/^[[:space:]]*buildNumber/{n;s/\(iOS: \)[0-9]*/\1myBuildNumber/;}" file
When buildNumber
found, n
reads the next line and searches iOS:
, followed by numbers. If found, the template is replaced with iOS
(using the backlink) and then myBuildNumber
.
Edit:
To edit the file under OSX, add the flag -i
:
sed -i '' "/^[[:space:]]*buildNumber/{n;s/\(iOS: \)[0-9]*/\1myBuildNumber/;}" file
source to share
Better to use awk for multi-line editing of records like:
awk '/buildNumber:/{p=NR} NR==p+1 && /iOS: [0-9]+/{sub(/iOS.*/, "iOS: myBuildNumber")} 1' file
dsplaySetting: 0
applicationIdentifier:
Android: com.appid.name
Standalone: com.appid.name
Tizen: com.appid.name
iOS: com.appid.name
tvOS: com.appid.name
buildNumber:
iOS: myBuildNumber
someOtherID: 190
moreIDsOverHere: 978987
source to share