bashformattingprintf

Create string based on array values


I am trying to create a tree structure like the tree command.

To keep track of the "heirarchy", I have an array like ("true" "true" "false") or ("true" "false" "false") or ("false" "true" "true") etc.

I want to build a string (that I will use to print the result on the terminal) which has Unicode based on the array.

For example ("true" "true" "false") would result in "│ │ "

("true" "false" "false") would result in in "│ "

and

("false" "true" "true") would result in " │ │ "

Where false is 2 spaces, true is unicode character \u2502 and a space. With the printf "%6s" | sed $'s/ /\u2502 /' command I can create spaces and replace one or all spaces (or 2 spaces) with unicode chars manually but I want to do it programmatically and also, the length on the array will change, doing manually can get very cumbersome.

Can someone guide? I am basically trying to add the lines in the places shown by red squiggles in the pic below

enter image description here


Solution

  • Using sed:

    sed 's/true/│ /g; s/false/  /g' <<< "${arr[*]}"