Summary Files Commits Branches @commit @diff @stats
path: root / awk-edits / #strings.awk
diff options
context:
space:
mode:
1 files changed, 40 insertions, 0 deletions
-rw-r--r--awk-edits/#strings.awk40
diff --git a/awk-edits/#strings.awk b/awk-edits/#strings.awk
index a34757e..3365df2 100644
--- a/awk-edits/#strings.awk
+++ b/awk-edits/#strings.awk
@@ -43,3 +43,43 @@ function gesub(regexp, exregexp, replacement, target) {
return result target;
}
+
+# glsub(lbregexp, regexp, largexp, replacement [, target])
+# Aka global sub with non-capturing look-around (lookbehind and lookahead)
+# Behaves kind of like gsub, however substitution of regexp with replacement
+# only happens, when regexp is preceded by lbregexp and succeeded by laregexp.
+# Only regexp get's replaced, the matches of lbregexp and laregexp are left
+# as-is. Overlapping of any form isn't supported.
+# This function is quite slow, try to use as little as possible.
+# Returns the result string, rather than doing it inplace.
+function glsub(lbregexp, regexp, laregexp, replacement, target) {
+ if (!length(target)) {
+ target = $0;
+ }
+
+ surlen = split(target, surrounds, lbregexp regexp laregexp);
+ result = surrounds[1];
+ # POSIX compliance, seps parameter in split isn't available
+ target = substr(target, length(surrounds[1]) + 1);
+ for (i = 2; i <= surlen; i++) {
+ if (surrounds[i] == "") {
+ match(target, lbregexp regexp laregexp);
+ si = RLENGTH + 1;
+ }
+ else {
+ si = index(target, surrounds[i]);
+ }
+ csep = substr(target, 1, si - 1);
+ target = substr(target, length(surrounds[i]) + si);
+
+ match(csep, regexp);
+ behind = substr(csep, 1, RSTART - 1);
+ ahead = substr(csep, RSTART + RLENGTH);
+ csep = substr(csep, RSTART, RLENGTH);
+
+ sub(/.*/, replacement, csep);
+ result = result behind csep ahead surrounds[i];
+ }
+
+ return result;
+}