Commit | Line | Data |
---|---|---|
ede080f6 SBS |
1 | #!/bin/bash |
2 | ||
3 | prune_path_rootside() { | |
4 | # Desc: Prunes a path from the root-side to a specified prune level. | |
5 | # Input: arg1 str path | |
6 | # arg2 int prune level (0-indexed) | |
7 | # Depends: GNU sed 4.8 | |
8 | # Version: 0.0.1 | |
9 | local path="$1"; | |
10 | local prune_level="$2"; | |
11 | ||
12 | # Check for absolute or relative path | |
13 | if [[ "$path" =~ ^/ ]]; then | |
14 | flag_root=true; | |
15 | # Remove initial / | |
16 | path="$(echo "$path" | sed -e 's:^/::' )"; | |
17 | else | |
18 | flag_root=false; | |
19 | fi; | |
20 | ||
21 | # Save path as array with `/` as element delimiter | |
22 | local IFS='/'; | |
23 | read -ra parts <<< "$path"; | |
24 | ||
25 | # Assemble pruned path from prune_level | |
26 | local pruned_path=""; | |
27 | for (( i=prune_level; i<${#parts[@]}; i++ )); do | |
28 | pruned_path+="${parts[i]}/"; | |
29 | done; | |
30 | ||
31 | # Trim trailing `/` delimiter | |
32 | pruned_path=$(echo "$pruned_path" | sed 's:/*$::'); | |
33 | ||
34 | # Restore initial / if appropriate | |
35 | if [[ "$flag_root" == "true" ]] && [[ "$prune_level" -eq 0 ]]; then | |
36 | pruned_path=/"$pruned_path"; | |
37 | fi; | |
38 | ||
39 | # Output pruned path | |
40 | echo "$pruned_path"; | |
41 | #declare -p path prune_level parts pruned_path && printf "========\n"; # debug | |
42 | return 0; | |
43 | }; # prune path rootside to int specified level | |
44 | ||
45 | printf "========Test 1========\n"; | |
46 | prune_path_rootside "foo/bar/baz" 0; | |
47 | prune_path_rootside "foo/bar/baz" 1; | |
48 | prune_path_rootside "foo/bar/baz" 2; | |
49 | prune_path_rootside "foo/bar/baz" 3; | |
50 | printf "========Test 2========\n"; | |
51 | prune_path_rootside "/foo/bar/baz" 0; | |
52 | prune_path_rootside "/foo/bar/baz" 1; | |
53 | prune_path_rootside "/foo/bar/baz" 2; | |
54 | prune_path_rootside "/foo/bar/baz" 3; |