6cea251bbba541001398509e6ad6ae3398a89de3
[BK-2020-03.git] / unitproc / bkt-insertStr
1 #!/usr/bin/env bash
2 # Desc: Insert string into provided string
3
4 yell() { echo "$0:${FUNCNAME[*]}: $*" >&2; }
5 die() { yell "$*"; exit 111; }
6 must() { "$@" || die "cannot $*"; }
7
8 insertStr() {
9 # Desc: Inserts a
10 # Input: arg1: str str_rec String to receive insertion
11 # arg2: int pos Insertion position (0 = append to front)
12 # arg3: str str_ins String to be inserted
13 # Output: stdout: Combined string
14 # Version: 0.0.1
15 # Depends: BK-2020-03: yell(), die(), must()
16 # Ref/Attrib: * BK-2020-03: https://gitlab.com/baltakatei/baltakatei-exdev/
17
18 local str_rec pos str_ins;
19
20 # Check args
21 if [[ $# -ne 3 ]]; then
22 yell "ERROR:Invalid argument count:$#";
23 return 1; fi;
24 re='^[0-9]+$';
25 if [[ ! "$2" =~ $re ]]; then
26 yell "ERROR:Not an int:$2";
27 return 1; fi;
28 str_rec="$1";
29 pos="$2";
30 str_ins="$3";
31
32 # Calculate string stats
33 len_str_rec="${#str_rec}";
34 len_str_ins="${#str_ins}";
35
36 # Form prefix
37 pfx_pos_start="0";
38 pfx_len="$pos";
39 pfx="${str_rec:$pfx_pos_start:$pfx_len}";
40
41 # Form suffix
42 sfx_pos_start="$(( pos ))";
43 sfx_len="$(( len_str_rec - pos ))";
44 sfx="${str_rec:$sfx_pos_start:$sfx_len}";
45
46 # Print output to stdout
47 printf "%s%s%s\n" "$pfx" "$str_ins" "$sfx";
48 }; # Insert string provided at indicated position via stdout
49
50
51 # Tests
52 printf "\"%s\" should read \"foobarbaz\"\n" "$(insertStr "foobaz" 3 "bar";)";
53
54 insertStr "foobaz" 0 "bar";
55 insertStr "foobaz" 1 "bar";
56 insertStr "foobaz" 2 "bar";
57 insertStr "foobaz" 3 "bar";
58 insertStr "foobaz" 4 "bar";
59 insertStr "foobaz" 5 "bar";
60 insertStr "foobaz" 6 "bar";
61 insertStr "foobaz" 7 "bar";
62 insertStr "foobaz" 999 "bar";