Home > Net >  Bash print long list as columns
Bash print long list as columns

Time:11-30

I have an array called nameVar, looks like this: 'server1' 'server2' 'server3' 'server4' With the following code:

echo "Which F5 to connect:"
for f5 in ${!nameVar[*]}
do
    printf "M: %s\n" $f5 ${nameVar[$f5]}
done

I receive a numbered list containig each item in the array.

0: server1
1: server2
2: server3

My issue is, if my array has a lot of items, the output is too long, I have to scroll up to see the beginning.

If I use \t instead of \n, the output is not pretty, due to the various lengths (eg. some has long name like server1-eastus-2021, some has short like server002).

How can I get pretty, column-like output?


| 0: server1     |   3: server1-eastus-2021  
| 1: server2     |   4: server5              
| 2: server3     |   5: server6              

CodePudding user response:

Assuming your list is a single column, you could just pipe through to less.

However, I believe the pretty look you are after can be obtained using pr

DESCRIPTION
       Paginate or columnate FILE(s) for printing.

If you wanted 2 or 3 columns for example, you can use

$ pr -2t input_file #2 columns
$ pr -3T input_file #3 columns

And so on.

$ echo "0: server1
1: server2
2: server3
3: server4
4: server5
5: server6" | pr -2T
0: server1                          3: Serer4
1: server2                          4: server5
2: server3                          5: server6

Or as noted by David C. Rankin and more like your expected output, you can go for an even prettier look.

$ .... | pr -2 -S" |   " -T
0: server1                        |       3: server4
1: server2                        |       4: server5
2: server3                        |       5: server6
  •  Tags:  
  • bash
  • Related