feat(unitproc/palign.sh):Add script to align path lists
[BK-2020-03.git] / unitproc / bkt-get_path_hierarchy_level
CommitLineData
0fc97e3e
SBS
1#!/bin/bash
2get_path_hierarchy_level() {
3 # Desc: Outputs hierarchy level of input paths
4 # Example: $ cat lines.txt | get_path_hierarchy_level
5 # Input: stdin str lines with /-delimited paths
6 # Output: stdout int hierarchy level of each path
7 # Version: 0.0.1
8
9 local line level;
10 local flag_root;
11 local -a output;
12
13 n=0;
14 while read -r line; do
15 # Check for mixed absolute/relative paths.
16 if [[ $n -le 0 ]] && [[ "$line" =~ ^/ ]]; then
17 flag_root=true;
18 else
19 flag_root=false;
20 fi;
21 if { [[ "$flag_root" == "true" ]] && [[ ! "$line" =~ ^/ ]]; } || \
22 { [[ "$flag_root" == "false" ]] && [[ "$line" =~ ^/ ]]; } then
23 echo "FATAL:Mixed relative and absolute paths not supported." 1>&2; return 1;
24 fi;
25
26 # Squeeze multiple slashes and remove trailing slashes
27 line="$(echo "$line" | tr -s '/' | sed 's:/*$::' )";
28
29 # Count the number of slashes to determine hierarchy level
30 level="$(echo "$line" | awk -F'/' '{print NF-1}' )";
31 if [[ "$flag_root" == "true" ]]; then ((level--)); fi;
32
33 # Append to output
34 output+=("$level");
4f51959a 35 #declare -p flag_root level; # debug
0fc97e3e
SBS
36 ((n++));
37 done;
38 # Print output
39 printf "%s\n" "${output[@]}";
4f51959a 40}; # return hierarchy level of lines as integers
0fc97e3e
SBS
41
42# Test the function with the provided lines
43printf "\n\n========Test 1========\n"
44input_lines=(
45 "foo"
46 "foo/"
47 "foo/bar"
48 "foo/bar/"
49 "foo/bar///"
50 "foo///bar"
51 "/foo/bar/baz"
52 "/foo/bar/baz/"
53 "//foo/bar/baz////"
54);
55
56printf "%s\n" "${input_lines[@]}";
57printf "========Test 1 results:========\n";
58# Convert array to newline-separated string and pass to function
59printf "%s\n" "${input_lines[@]}" | get_path_hierarchy_level
60
61printf "\n\n========Test 2========\n"
62input_lines=(
63 "foo"
64 "foo/"
65 "foo/bar"
66 "foo/bar/"
67 "foo/bar///"
68 "foo///bar"
69 "foo/bar/baz"
70 "foo/bar/baz/"
71 "foo/bar/baz////"
72);
73
74printf "%s\n" "${input_lines[@]}";
75printf "========Test 2 results:========\n";
76# Convert array to newline-separated string and pass to function
77printf "%s\n" "${input_lines[@]}" | get_path_hierarchy_level