Pradeep BS
Pradeep BS

Reputation: 51

Sed to replace previous line

I am trying to replace the previous line of a string match.

Example json

  "test" : {
    "aa" : true,
    "ac" : "port",
    "tr" : "p2",
    "ll" : 90,
    "mp" : true
  }

If "ll" equals 90, I need to change the previous line to "mu" : "p1". I have tried the below sed but it always replaces the same line instead on the previous line. Please suggest

sed -e '/"ll" : 90/!b;!N;c"mu" : "p1"'

Upvotes: 0

Views: 966

Answers (1)

sat
sat

Reputation: 14949

You can try this sed:

sed 'N;/\n *"ll" : 90/{s/^\([^"]*\).*\n/\1"mu" : "p1",\n/;};P;D' file

As suggested by @potong,

sed -r 'N;s/.*(\n(\s*)"ll" : 90,)/\2"mu : "p1",\1/;P;D' file

Output:

"test" : {
  "aa" : true,
  "ac" : "port",
  "mu" : "p1",
  "ll" : 90,
  "mp" : true
}

Upvotes: 2

Related Questions