Create indent text using bash

I want to print the list on screen in a readable way. I use a loop to go through each item and create a new list that is formatted with commas and new characters. The problem is that in the first line of the output, I want a header. For example, I want to print something like this:

List: red, green, blue, black, cars, busses, ... 

The problem is indenting the second and subsequent lines. I want the padding to be the given length. Therefore, the problem boils down to creating an empty string of a given length. That is, I want the create_empty_line_of_length function, which outputs a given number of spaces.

 length=5 echo "start:$(create_empty_line_of_length $length) hello" 

In this case, the output should be:

 start: hello 

Does anyone know how to do this?

+6
string bash
source share
3 answers

This will

 yes ' ' | head -7 | tr -d '\n' 

Change โ€œ7โ€ to your number.

Maybe you should take a look at

 man fmt 

also.

+6
source share
  printf '%7s' 

This is probably the most effective way to do this.

Its shell is built in most of the time, and if not / usr / bin / printf exists as a backup from coreutils.

So

  printf '%7s%s\n%7s%s\n' '_' 'hello' '_' 'world' 

produces

  _hello _world 

(instead, I used _ instead of space, but space also works because bash understands')

+9
source share
+1
source share

All Articles