2 # Desc: Insert string into provided string
4 yell
() { echo "$0: $*" >&2; }
5 die
() { yell
"$*"; exit 111; }
6 must
() { "$@" || die
"cannot $*"; }
8 # Desc: Inserts a string into another string at a specified position.
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
14 # Depends: BK-2020-03: yell(), die(), must()
15 # Ref/Attrib: * BK-2020-03: https://gitlab.com/baltakatei/baltakatei-exdev/
16 # * Cooper, Mendel. “Advanced Bash-Scripting Guide: Manipulating Strings”. tldp.org https://tldp.org/LDP/abs/html/string-manipulation.html
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
;
23 if [[ $# -ne 3 ]]; then
24 yell
"ERROR:Invalid argument count:$#";
27 if [[ ! "$2" =~
$re ]]; then
28 yell
"ERROR:Not an int:$2";
34 # Calculate string stats
35 len_str_rec
="${#str_rec}";
40 pfx
="${str_rec:$pfx_pos_start:$pfx_len}";
43 sfx_pos_start
="$(( pos ))";
44 sfx_len
="$(( len_str_rec - pos ))";
45 sfx
="${str_rec:$sfx_pos_start:$sfx_len}";
47 # Print output to stdout
48 printf "%s%s%s\n" "$pfx" "$str_ins" "$sfx";
49 }; # Insert string provided at indicated position via stdout
53 printf "\"%s\" should read \"foobarbaz\"\n" "$(insertStr "foobaz
" 3 "bar
";)";
55 insertStr
"foobaz" 0 "bar";
56 insertStr
"foobaz" 1 "bar";
57 insertStr
"foobaz" 2 "bar";
58 insertStr
"foobaz" 3 "bar";
59 insertStr
"foobaz" 4 "bar";
60 insertStr
"foobaz" 5 "bar";
61 insertStr
"foobaz" 6 "bar";
62 insertStr
"foobaz" 7 "bar";
63 insertStr
"foobaz" 999 "bar";