# gosub(regexp, replacement [, target]) # Aka global original sub # Behaves like gsub, however doesn't try regexp on previoud replacements # and returns the result string, rather than doing it inplace. function gosub(regexp, replacement, target) { if (!length(target)) { target = $0; } result = ""; matched = ""; while (match(target, regexp)) { result = result substr(target, 1, RSTART - 1); matched = substr(target, RSTART, RLENGTH); target = substr(target, RSTART + RLENGTH); sub(regexp, replacement, matched); result = result matched; } return result target; } # gesub(regexp, exregexp, replacement [, target]) # Aka global excluding sub # Behaves like gsub, however substitutes only where exregexp doesn't match # and returns the result string, rather than doing it inplace. function gesub(regexp, exregexp, replacement, target) { if (!length(target)) { target = $0; } result = ""; while (match(target, exregexp)) { beg = substr(target, 1, RSTART - 1); exclude = substr(target, RSTART, RLENGTH); target = substr(target, RSTART + RLENGTH); gsub(regexp, replacement, beg); result = result beg exclude; } gsub(regexp, 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 the lookahead and lookbehind substrings is supported, # but any sort of overlapping which includes regexp isn't. # 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; } result = "" match(target, lbregexp regexp); while (RLENGTH > -1) { result = result substr(target, 1, RSTART - 1); matched = substr(target, RSTART, RLENGTH); target = substr(target, RSTART + RLENGTH); match(target, laregexp); if (RSTART == 1) { match(matched, regexp); result = result substr(matched, 1, RSTART - 1); matched = substr(matched, RSTART); sub(/.*/, replacement, matched); } result = result matched; match(target, lbregexp regexp); } return result target; } }