Make echo “autofill” a line of certain width

2019-03-04 10:49发布

问题:

I have a rather large bash script which reads in a number of variables and then echoes them. I have no way to know beforehand the length of these variables and I do not want to shorten them or format them in any way - I just want them echoed in the same form they are read in.

To improve readability of my script's output I am echoing some lines to help the eye, something like this:

echo "--------------------------------"
echo "Here come some variables       |"
echo "                               |"
echo "a = $a and b = $b"
echo "                               |"
echo "End of the script              |"
echo "--------------------------------"

This will output:

--------------------------------
Here come some variables       |
                               |
a = 1.23e-19 and b = hello
                               |
End of the script              |
--------------------------------

What I want to achieve is for echo (or some alternative solution) to recognize how many empty spaces it needs to insert after the variables are printed so it can align a vertical line | with the rest of them, so that this output looks like this:

--------------------------------
Here come some variables       |
                               |
a = 1.23e-19 and b = hello     |
                               |
End of the script              |
--------------------------------

It does not need to be an echo only solution, but I would appreciate simplicity. Any ideas?

回答1:

I don't have access to a linux machine now, but there also is printf that can be used on the command line. So you could use printf " a = %10s and b= %10s |\n" "$a" $b".

You can play with the format specifiers to improve the result.



回答2:

So elaborating a bit on Axel's answer using printfcan do this. If the line width is linewidth then:

a="1.23e-19" 
b="hello"
linewidth=30
echo "--------------------------------"
echo "Here come some variables       |"
echo "                               |"
printf "%-${linewidth}s |\n" "a = $a and b = $b"
echo "                               |"
echo "End of the script              |"
echo "--------------------------------"

does exactly what I want. Output:

--------------------------------
Here come some variables       |
                               |
a = 1.23e-19 and b = hello     |
                               |
End of the script              |
--------------------------------


标签: bash echo