summaryrefslogtreecommitdiffstats
path: root/research/split.sh
blob: d003fa4343eb16867efb0fad4efb3064d6903a6a (plain)
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
# This is the lexer's old file-splitting code:
#	eval "$(printf '%s' "${buf}" | awk -v FS='' -v j=0 \
#		-v squote="'" -v esc_squote="'\\\\''" '
#		{
#			for (i = 1; i <= NF; ++i) {
#				sub(squote, esc_squote, $i);
#				printf("lbufv_%d=" squote "%s" squote "\n",
#					j++, $i);
#			};
#			printf("lbufv_%d=" squote "\n" squote "\n", j++);
#		}
#		')"
# It relies on behavior specific to GNU awk.
# POSIX on awk's FS: "If FS is a null string, the behavior is unspecified."
# Cf. <http://stackoverflow.com/a/31135987> regarding other implementations.
# So we need to get even more creative.

US="$(printf '\037.')"; US="${US%.}"

buf='Hello, world!
Hi!
'

# Use sed to preprocess the buffer and give awk a proper field separator.
printf '%s' "${buf}" | sed "s/\\(.\\)/\\1${US}/g" | \
	awk -v FS="${US}" -v j=0 -v squote="'" -v esc_squote="'\\\\''" '
	{
		for (i = 1; i <= NF; ++i) {
			if ($i == "") {
				continue;
			}
			sub(squote, esc_squote, $i);
			printf("lbufv_%d=" squote "%s" squote "\n",
				j++, $i);
		};
		printf("lbufv_%d=" squote "\n" squote "\n", j++);
	}
	'

# And we might as well get rid of awk and use sed and SCL.
i=0
IFS="${US}"
for c in $(printf '%s' "${buf}" | sed -n "
		1h;   # Put the first line in the hold space.
		1!H;  # Append to the hold space each subsequent line.
		\${   # Once the hold space contains the whole buffer...
			g;  # Prepare to edit the buffer.
			s/\\(.\\)/\\1${US}/g;  # Put US after each char.
			p;  # Print the result.
		};
		"); do
	printf "lbufv_%d='%s'\n" ${i} "${c}"
	i=$((${i} + 1))
done
unset IFS