I have input files with a structure like the following:
a1
b1
c1
c2
c3
b2
c1
d1
d2
b3
b4
a2
a3
b1
b2
c1
c2
Each level is indented by 2 spaces. Required Output:
a1/b1/c1
a1/b1/c2
a1/b1/c3
a1/b2/c1/d1
a1/b2/c1/d2
a1/b3
a1/b4
a2
a3/b1
a3/b2/c1
a3/b2/c2
This is similar to the file system if the next line has a larger indent, the current line is like a βdirectoryβ, and when it has the same indent, it looks like a βfileβ. You need to print the full paths of the "files".
Trying to solve this without any high-level language, for example python, perlonly with basic bash commands.
My current code / idea is based on a recursive function call and working with glass, but the problem is with the "logic". The code currently displays the following:
a1 b1 c1
a1 b1
a1
DD: line 8: [0-1]: bad array subscript
only the 1st row is ok - so recursion processing is wrong ...
input="ifile.tree"
declare -a stack
pushstack() { stack+=("$1"); }
popstack() { unset stack[${#stack[@]}-1]; }
printstack() { echo "${stack[*]}"; }
checkline() {
local uplev=$1
read -r level text || (printstack; exit 1) || return
if [[ $uplev < $level ]]
then
pushstack "$text"
checkline $level
fi
printstack
popstack
}
(
IFS=,
while read -r spaces content
do
echo $(( (${#spaces} / 2) + 1 )) "$content"
done < <(sed 's/[^ ]/,&/' < "$input")
) | (
checkline 0
)
Sry for long code - can anyone help?