Reputation: 3
I'm using Bash. I am using printf "%-40s%s" $a $b
to display two strings in two columns. The second string is very long and is overflowing and printing at the beginning of the next line in the first column. How can I make the string in the second column overflow into the second column?
Upvotes: 0
Views: 226
Reputation: 80931
This is not pretty and I still feel like it could be better (but I don't see any obvious ways of making it better) but it works (thought doesn't have correct alignment for the first column) for me:
col.sh:
#!/bin/bash
a=$1
b=$2
w=${3:-$(tput cols)}
fmta=$(fold -w 40 <<<"$a")
lca=$(wc -l <<<"$fmta")
fmtb=$(fold -w $(( w - 40 )) <<<"$b")
lcb=$(wc -l <<<"$fmtb")
if [ "$lca" -lt "$lcb" ]; then
fmta+=$(printf ' \n%.0s' $(seq 0 $(( lcb - lca ))))
fi
pr -t -2 <<<"$fmta"$'\n'"$fmtb"
Run as:
$ a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
$ b=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
$ ./col.sh "$a" "$b"
Takes a third optional argument for terminal width for when $(tput cols)
doesn't work. Can probably use ./col.sh "$a" "$b" "$COLUMNS"
.
Upvotes: 0
Reputation: 785068
You can use:
printf "%40s\n%40s\n" "aaaaaaaaaaaaaaaaaaaaaaaaaaa" "bbbbbbbbbbbbbbbbbbbbbbbbbbb"
aaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbb
-
before 40
is for left alignment.
Upvotes: 1