Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating indented text with bash

Tags:

string

bash

I want to print a list to screen in a readable way. I use a loop to go through each element and make a new list which is formatted with commas and newlines. The problem is that in the first line of the output, I want a title. E.g., I want to print something like this:

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

The problem is to create the indentation in the second and following lines. I want the indentation to be of a given length. Therefore the problem is reduced to creating an empty line of a given length. That is, I want a function, create_empty_line_of_length, that outputs the given amount of spaces.

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

The output should in this case be:

start:      hello

Does anyone know how to do this?

like image 296
Karl Yngve Lervåg Avatar asked Jan 20 '09 12:01

Karl Yngve Lervåg


1 Answers

 printf '%7s' 

Will probably the most efficient way to do it.

Its a shell builtin most of the time, and if not /usr/bin/printf exists as a fallback from coreutils.

so

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

produces

      _hello
      _world

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

like image 134
Kent Fredric Avatar answered Sep 29 '22 09:09

Kent Fredric