Reputation: 1378
I'd like to know how I could replace a line that contains a pattern but only if the prior line has another pattern using sed. I have a text file that contains the following:
Property: ONE
Value: some_value
Property: TWO
Value: some_value
Property: THREE
Value: some_other_value
So I want to find a line containing some_value and replace the entire line with another line or just update the value but only if the property line contains word ONE. The end result would looks like so
Property: ONE
Value: replaced_value
Property: TWO
Value: some_value
Property: THREE
Value: some_other_value
Upvotes: 3
Views: 991
Reputation: 203254
Just use awk:
$ awk 'p~/Property: ONE/{$NF="replaced_value"} {p=$0; print}' file
Property: ONE
Value: replaced_value
Property: TWO
Value: some_value
Property: THREE
Value: some_other_value
Upvotes: 0
Reputation: 157947
You can use sed
like this:
sed '/Property: ONE/{n;s/Value:.*/Value: replaced_value/}' file
Once the pattern Property: ONE
is found, I read the next line into the pattern buffer using the n
command and substitute the value using the s
command.
Upvotes: 5
Reputation: 785008
You can use awk
awk 'BEGIN{FS=OFS=": "} p {
$2 = "replaced_value"
}
{
p = ($0 ~ /^Property: *ONE/ ? 1 : 0)
} 1' file
Property: ONE
Value: replaced_value
Property: TWO
Value: some_value
Property: THREE
Value: some_other_value
Upvotes: 0