#!/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