Aaron Bandelli
Aaron Bandelli

Reputation: 1378

sed replace a line if prior line match pattern

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

Answers (3)

Ed Morton
Ed Morton

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

hek2mgl
hek2mgl

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

anubhava
anubhava

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

Related Questions