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