awk - Sed: Complicated replace after pattern (on same line) -
suppose have text this:
foobar 42 | ff 00 00 00 00 foobaz 00 | 0a 00 0b 00 00 foobie 00 | 00 00 00 00 00 bar 00 | ab ba 00 cd 00
and want change non-00
on right hand side of |
wrapped ()
, if on lhs of |
has 00
. desired result:
foobar 42 | ff 00 00 00 00 foobaz 00 | (0a) 00 (0b) 00 00 foobie 00 | 00 00 00 00 00 bar 00 | (ab) (ba) 00 (cd) 00
is there way of going using sed, or trying stretch beyond capabilities of language?
here's work far:
s/[^0]\{2\}/(&)/g
wraps rhs values
/[^|]*00[^|]*|/
can used address command operate on valid lines
the trick formulate command executes in portion of pattern space.
this isn't line oriented, may explain why i'm having trouble getting expression works.
$ awk 'begin{ fs=ofs="|" } $1~/ 00 /{gsub(/[^ ][^0 ]|[^0 ][^ ]/,"(&)",$2)} 1' file foobar 42 | ff 00 00 00 00 foobaz 00 | (0a) 00 (0b) 00 00 foobie 00 | 00 00 00 00 00 bar 00 | (ab) (ba) 00 (cd) 00
in case string want search ever gets more complicated 2 0s, here's more extensible approach since doesn't require write re negates string:
$ awk ' begin{ fs=ofs="|" } $1 ~ / 00 /{ split($2,a,/ /) $2="" (i=2;i in a;i++) $2 = $2 " " (a[i] == "00" ? a[i] : "(" a[i] ")") } 1 ' file foobar 42 | ff 00 00 00 00 foobaz 00 | (0a) 00 (0b) 00 00 foobie 00 | 00 00 00 00 00 bar 00 | (ab) (ba) 00 (cd) 00
Comments
Post a Comment