feat(user/rand_media_pl.sh):Script to play random position of media
[BK-2020-03.git] / unitproc / bkt-insertStr
1 #!/usr/bin/env bash
2 # Desc: Insert string into provided string
3
4 yell() { echo "$0: $*" >&2; }
5 die() { yell "$*"; exit 111; }
6 must() { "$@" || die "cannot $*"; }
7 insertStr() {
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
13 # Version: 0.0.2
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
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;
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}";
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
48 printf "%s%s%s\n" "$pfx" "$str_ins" "$sfx";
49 }; # Insert string provided at indicated position via stdout
50
51
52 # Tests
53 printf "\"%s\" should read \"foobarbaz\"\n" "$(insertStr "foobaz" 3 "bar";)";
54
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";