views:

633

answers:

3

Hello. 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?

+2  A: 

It'll be

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

Change '7' into your number.

Maybe you should take a look at

man fmt

also.

squadette
+5  A: 
 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 ' ' )

Kent Fredric
Shouldn't there be seven '_'s in front of 'hello' and 'world'? Anyway, thank you. It worked :)
Karl Yngve Lervåg
Nah, "%7s" is a pure alignment rule, it says "take a string, and right align it with position 7, ie: it will only create space. '%2s' 'hello world' will not add any space, because "hello world" is larger than 2, but '%40s\n%40s\n' 'hello' 'world' will right align hello and world with pos 40
Kent Fredric
Oh, thanks! That is useful!
Karl Yngve Lervåg
+1  A: 

Not sure if this is going to help you http://unstableme.blogspot.com/2008/12/awk-formatting-fields-into-columns.html

It is not needed for the problem I had before asking this question, no. It is inspiring, though! I shall look more into how to use awk, as it seems to be a powerful tool. :)
Karl Yngve Lervåg