Summary Files Commits Branches @commit @diff @stats
path: root / awk-edits / #strings.awk
blob: 074e42a67d0ea46cb4aa4ac00cf3423fbdb82f6c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 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 [, empt, target])
# Aka global sub with non-capturing look-around (lookbehind and lookahead)
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 laregxep);
			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;
}