From: Steven Baltakatei Sandoval Date: Wed, 17 Jul 2024 02:25:04 +0000 (+0000) Subject: feat(unitproc/bkt-prune_path_rootside):Add Bash function X-Git-Url: https://zdv2.bktei.com/gitweb/BK-2020-03.git/commitdiff_plain/ede080f66be6d19f701d1bffea26229fc9343e35?ds=sidebyside;hp=0fc97e3eeb52abebc4d972e128ad206ab10386da feat(unitproc/bkt-prune_path_rootside):Add Bash function --- diff --git a/unitproc/bkt-prune_path_rootside b/unitproc/bkt-prune_path_rootside new file mode 100755 index 0000000..9736299 --- /dev/null +++ b/unitproc/bkt-prune_path_rootside @@ -0,0 +1,54 @@ +#!/bin/bash + +prune_path_rootside() { + # Desc: Prunes a path from the root-side to a specified prune level. + # Input: arg1 str path + # arg2 int prune level (0-indexed) + # Depends: GNU sed 4.8 + # Version: 0.0.1 + local path="$1"; + local prune_level="$2"; + + # Check for absolute or relative path + if [[ "$path" =~ ^/ ]]; then + flag_root=true; + # Remove initial / + path="$(echo "$path" | sed -e 's:^/::' )"; + else + flag_root=false; + fi; + + # Save path as array with `/` as element delimiter + local IFS='/'; + read -ra parts <<< "$path"; + + # Assemble pruned path from prune_level + local pruned_path=""; + for (( i=prune_level; i<${#parts[@]}; i++ )); do + pruned_path+="${parts[i]}/"; + done; + + # Trim trailing `/` delimiter + pruned_path=$(echo "$pruned_path" | sed 's:/*$::'); + + # Restore initial / if appropriate + if [[ "$flag_root" == "true" ]] && [[ "$prune_level" -eq 0 ]]; then + pruned_path=/"$pruned_path"; + fi; + + # Output pruned path + echo "$pruned_path"; + #declare -p path prune_level parts pruned_path && printf "========\n"; # debug + return 0; +}; # prune path rootside to int specified level + +printf "========Test 1========\n"; +prune_path_rootside "foo/bar/baz" 0; +prune_path_rootside "foo/bar/baz" 1; +prune_path_rootside "foo/bar/baz" 2; +prune_path_rootside "foo/bar/baz" 3; +printf "========Test 2========\n"; +prune_path_rootside "/foo/bar/baz" 0; +prune_path_rootside "/foo/bar/baz" 1; +prune_path_rootside "/foo/bar/baz" 2; +prune_path_rootside "/foo/bar/baz" 3;