Is there an example of indenting strings in Bash (for output)?
I found examples using printf
but they don't seem to work as expected.
I want to simply indent a given string with a given number of spaces.
echo "Header"
indent "Item 1" 2
indent "Sub Item 1a" 4
indent "Sub Item 1b" 4
would produce the output
Header
Item 1
Sub Item 1a
Sub Item 1b
In printf
, something like %3s
means "a string, but with as many initial spaces as are necessary to ensure that the string is at least 3
columns wide".
This works even if the string is the empty string ''
, in which case %3s
means essentially "three spaces".
So, for example, indent "Sub Item 1a" 4
can be expressed as printf '%4s%s\n' '' "Sub Item 1a"
, which prints four spaces followed by "Sub Item 1a"
and a newline.
If you want, you can implement indent
as a function:
function indent () {
local string="$1"
local num_spaces="$2"
printf "%${num_spaces}s%s\n" '' "$string"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With