Kvothe
Kvothe

Reputation: 285

sed replacement dependent on surroundings

How do I do a sed replacement on a file containing things like f[3][2,3][4] which should be replaced by f[3][2,3]["string"][4]. Of course the numbers could be different numbers and I want the same replacement to happen. Here we need to give full pattern, something like

f\[[0-9]*\]\[[0-9]*,[0-9]*\]

to pick out the right part but then I need the replacement to give the same numbers that where matched earlier (as well as attaching ["string"]). What is the best way to do this?

Upvotes: 1

Views: 41

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

sed 's/\(f\[[0-9]*]\[[0-9]*,[0-9]*]\)\[\([0-9]*\)]/\1["string"][\2]/g'

Or

sed -E 's/(f\[[0-9]*]\[[0-9]*,[0-9]*])\[([0-9]*)]/\1["string"][\2]/g'

See the online sed demo

Basically, capture the first part from f to the third index, and capture the number in the third index, too. Then, reference these values with \1 and \2 placeholders from the RHS.

Details

  • (f\[[0-9]*]\[[0-9]*,[0-9]*]) (ERE, in BRE, the (...) must be escaped) - Group 1 matching f[, 0+ digits, ][, 0+ digits, , and 0+ digits followed with ]
  • \[ - a [
  • ([0-9]*) - Group 2: 0+ digits
  • ] - a ] char.

Upvotes: 2

Related Questions