Bash: Wrap Long Lines Inside the Same Column

Actually, the util-linux 'column' command can do it. It is very versatile.

#!/bin/bash

cat <<- EOF | column --separator '|' \
                     --table \
                     --output-width 30 \
                     --table-noheadings \
                     --table-columns C1,C2 \
                     --table-wrap C2
key1|Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
key2|blahhhhhhhhhhhhhhhhhhhhhhhhhhhhzzz
EOF

This gives :

key1  Lorem ipsum dolor sit am
      et, consectetur adipisci
      ng elit, sed do eiusmod
      tempor incididunt ut lab
      ore et dolore magna aliq
      ua.
key2  blahhhhhhhhhhhhhhhhhhhhh
      hhhhhhhzzz

--output-width : give desired size (can use 'tput cols' as described above)

--table-columns C1,C2 : give names to columns to be used with other options

--table-wrap C2 : wrap column 2

Column version :

# column -V
column from util-linux 2.33.1

Solution based on andlrc's comment:

columnize2 () { 
    indent=$1; 
    collen=$(($(tput cols)-indent)); 
    keyname="$2"; 
    value=$3; 
    while [ -n "$value" ] ; do 
        printf "%-10s %-${indent}s\n" "$keyname" "${value:0:$collen}";  
        keyname="";
        value=${value:$collen}; 
    done
}

longvalue=---------------------------------------------------------------------xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
columnize2 30 key1 $longvalue
key1       --------------------------------------------------
           -------------------xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
           xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzz

tput cols returns the amount of characters per line in the terminal window. We use this to determine how many characters of the value we can print per line (collen). If it does not fit on one line, the rest is printed on the following lines. %-10s in the print statement is used to allocate 10 characters to display the keyname (long keys are not handled well). %-${indent}s is used to indent the value by #indent characters. Only print as many characters of the value as will fit on one line:${value:0:$collen} and strip the already printed characters from the value value=${value:$collen} For following lines we don't print the keyname (by setting it to an empty string).