6cea251bbba541001398509e6ad6ae3398a89de3
2 # Desc: Insert string into provided string
4 yell
() { echo "$0:${FUNCNAME[*]}: $*" >&2; }
5 die
() { yell
"$*"; exit 111; }
6 must
() { "$@" || die
"cannot $*"; }
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
15 # Depends: BK-2020-03: yell(), die(), must()
16 # Ref/Attrib: * BK-2020-03: https://gitlab.com/baltakatei/baltakatei-exdev/
18 local str_rec pos str_ins
;
21 if [[ $# -ne 3 ]]; then
22 yell
"ERROR:Invalid argument count:$#";
25 if [[ ! "$2" =~
$re ]]; then
26 yell
"ERROR:Not an int:$2";
32 # Calculate string stats
33 len_str_rec
="${#str_rec}";
34 len_str_ins
="${#str_ins}";
39 pfx
="${str_rec:$pfx_pos_start:$pfx_len}";
42 sfx_pos_start
="$(( pos ))";
43 sfx_len
="$(( len_str_rec - pos ))";
44 sfx
="${str_rec:$sfx_pos_start:$sfx_len}";
46 # Print output to stdout
47 printf "%s%s%s\n" "$pfx" "$str_ins" "$sfx";
48 }; # Insert string provided at indicated position via stdout
52 printf "\"%s\" should read \"foobarbaz\"\n" "$(insertStr "foobaz
" 3 "bar
";)";
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";