diff options
| Commit | 722a7d215ae0fd408b8b9c6fe2733fd093ce570c (patch) | |
|---|---|---|
| Author | 2023-05-05 14:15:17 +0300 | |
| Committer | 2023-05-05 14:15:17 +0300 | |
| Files | 0980d554020495c471cbeced4e65168861331b86 /awk-edits/#strings.awk | |
| syndamia.com-722a7d215ae0fd408b8b9c6fe2733fd093ce570c.tar syndamia.com-722a7d215ae0fd408b8b9c6fe2733fd093ce570c.tar.gz syndamia.com-722a7d215ae0fd408b8b9c6fe2733fd093ce570c.zip | ||
| Parent | acfb7f1a84ac6594c3e7c9929eb082ca3a5f4344 (diff) | |
[#strings] Implemented gbsub
1 files changed, 50 insertions, 0 deletions
| -rw-r--r-- | awk-edits/#strings.awk | 50 |
diff --git a/awk-edits/#strings.awk b/awk-edits/#strings.awk index 5e214cb..5c4e795 100644 --- a/awk-edits/#strings.awk +++ b/awk-edits/#strings.awk @@ -80,4 +80,54 @@ function glsub(lbregexp, regexp, laregexp, replacement, target) { return result target; } +# gbsub(lbrace, rbrace, replacement [, target ]) +# Aka global brace sub +# Properly substitutes recursive braced expressions, i.e. +# for "((1+2) * (3/(4-9)))", substitution is done first +# on "(1+2)", then on "(4-9)", afterwards on "(3/SOMETHING)" +# (where "(4-9)" turns into "SOMETHING" after substitution), +# and finally, the whole equation (with it's inner stuff +# substituted) is substituted. +# This is useful when one of the braces can exist as-is, but +# can also be paired with a special (opening/closing) brace. +# For example, in bash parameter expansion is specified with +# "${...}", however "}" can also be the closing brace of a function. +function gbsub(lbrace, rbrace, replacement, target) { + if (!length(target)) { + target = $0; + } + + result = substr(target, 1, match(target, lbrace) - 1); + depth = 1; + LLN = 0; + while (!(LLN == -1 && depth == 1)) { + match(target, lbrace); LST = RSTART; LLN = RLENGTH; + match(target, rbrace); + + # rbrace, pop stack + if (depth > 1 && (LST == 0 || LST > RSTART)) { + depth--; + level[depth] = level[depth] substr(target, 1, RSTART + RLENGTH - 1); + sub(/.*/, replacement, level[depth]); + if (depth > 1) { + level[depth - 1] = level[depth - 1] level[depth]; + } + else { + result = result level[1]; + level[1] = ""; + } + target = substr(target, RSTART + RLENGTH); + } + # lbrace, push stack + else if (LST > 0 && LST < RSTART) { + if (depth > 1) prev = depth - 1; + else prev = depth; + + level[prev] = level[prev] substr(target, 1, LST - 1); + level[depth++] = substr(target, LST, LLN); + target = substr(target, LST + LLN); + } + } + + return result target; } |