From: Steven Baltakatei Sandoval Date: Wed, 17 Jul 2024 00:03:24 +0000 (+0000) Subject: feat(unitproc/bkt-get_path_hierarchy_level):Add bash function X-Git-Url: https://zdv2.bktei.com/gitweb/BK-2020-03.git/commitdiff_plain/0fc97e3eeb52abebc4d972e128ad206ab10386da?ds=sidebyside feat(unitproc/bkt-get_path_hierarchy_level):Add bash function --- diff --git a/unitproc/bkt-get_path_hierarchy_level b/unitproc/bkt-get_path_hierarchy_level new file mode 100755 index 0000000..a76cb1f --- /dev/null +++ b/unitproc/bkt-get_path_hierarchy_level @@ -0,0 +1,77 @@ +#!/bin/bash +get_path_hierarchy_level() { + # Desc: Outputs hierarchy level of input paths + # Example: $ cat lines.txt | get_path_hierarchy_level + # Input: stdin str lines with /-delimited paths + # Output: stdout int hierarchy level of each path + # Version: 0.0.1 + + local line level; + local flag_root; + local -a output; + + n=0; + while read -r line; do + # Check for mixed absolute/relative paths. + if [[ $n -le 0 ]] && [[ "$line" =~ ^/ ]]; then + flag_root=true; + else + flag_root=false; + fi; + if { [[ "$flag_root" == "true" ]] && [[ ! "$line" =~ ^/ ]]; } || \ + { [[ "$flag_root" == "false" ]] && [[ "$line" =~ ^/ ]]; } then + echo "FATAL:Mixed relative and absolute paths not supported." 1>&2; return 1; + fi; + + # Squeeze multiple slashes and remove trailing slashes + line="$(echo "$line" | tr -s '/' | sed 's:/*$::' )"; + + # Count the number of slashes to determine hierarchy level + level="$(echo "$line" | awk -F'/' '{print NF-1}' )"; + if [[ "$flag_root" == "true" ]]; then ((level--)); fi; + + # Append to output + output+=("$level"); + #declare -p flag_root level; + ((n++)); + done; + # Print output + printf "%s\n" "${output[@]}"; +}; + +# Test the function with the provided lines +printf "\n\n========Test 1========\n" +input_lines=( + "foo" + "foo/" + "foo/bar" + "foo/bar/" + "foo/bar///" + "foo///bar" + "/foo/bar/baz" + "/foo/bar/baz/" + "//foo/bar/baz////" +); + +printf "%s\n" "${input_lines[@]}"; +printf "========Test 1 results:========\n"; +# Convert array to newline-separated string and pass to function +printf "%s\n" "${input_lines[@]}" | get_path_hierarchy_level + +printf "\n\n========Test 2========\n" +input_lines=( + "foo" + "foo/" + "foo/bar" + "foo/bar/" + "foo/bar///" + "foo///bar" + "foo/bar/baz" + "foo/bar/baz/" + "foo/bar/baz////" +); + +printf "%s\n" "${input_lines[@]}"; +printf "========Test 2 results:========\n"; +# Convert array to newline-separated string and pass to function +printf "%s\n" "${input_lines[@]}" | get_path_hierarchy_level