Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Indent a String in Bash using printf?

Tags:

bash

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
like image 816
IntrovertedRoot Avatar asked Mar 11 '23 15:03

IntrovertedRoot


1 Answers

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"
}
like image 101
ruakh Avatar answered Mar 17 '23 07:03

ruakh