6

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?

3 Answers 3

9
 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 ' ' )

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't there be seven '_'s in front of 'hello' and 'world'? Anyway, thank you. It worked :)
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
6

It'll be

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

Change '7' into your number.

Maybe you should take a look at

man fmt 

also.

Comments

1

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

1 Comment

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. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.