Search code examples
regexangularshellregex-lookarounds

Shell script/regex to replace sentences except for a keyword in the middle (refactoring Angular directives)


I need to replace all Angular translation directives with those from ngx.

In short this means changing:

<dt i18n="test label@@testLabel">test</dt>

to

<dt [translate]="'testLabel'">test</dt>

Note the extra ' that surrounds the label name.

It's fairly simple to just select i18n=" and change it into [translate]="' with a regex however my code will not compile then as my label will be missing a '.

I continued to try a script

SomeText2="<dt i18n=\"testLabel@@testLabel\">Test</dt>"


REGEX_REP= echo $SomeText2 | sed 's/i18n="/\[translate\]="/' | sed 's/@@//'| sed s/\"/\'\"/2

But this will just put an apostrophe infront of every quotation mark. So I think I'm looking for a regex that can check if there is a certain string ( [translate] e.g.) somewhere in front of it so I can replace " with '".

Or if someone else has any better ideas let me know! thanks


Solution

  • You may use

    REGEX_REP="$(echo "$SomeText2" | sed 's/i18n="[^"]*@@\([^"]*\)"/[translate]="'"'"'\1'"'"'"/')"
    

    See the online demo, output is <dt [translate]="'testLabel'">Test</dt>.

    The i18n="[^"]*@@\([^"]*\)" pattern matches i18n=" substring, then [^"]* matches any 0+ chars other than ", @@ matches @@, \([^"]*\) captures into Group 1 any zero or more chars other than " and " matches a double quote.

    The replacement is [translate]="'\1'", that is [translate]="'<Group 1 value>'".