简体   繁体   中英

Bash Split by column printf output

For a menu, i'm trying to split the following output with a printf. Actually, the output is made on one column, the goal is to split the output into severals columns of 20 or 30 elements.

The text file is composed with the following items nearly 100:

item1
item2
item3
...
item98
item99
item100

Here the code. I tried with %-xxs without success.

LST_SRV_PSI=lst.txt
mapfile -t HOSTTAB < "$LST_SRV_PSI"
for i in ${!HOSTTAB[@]}; do
    #printf "%3d%s) %s\n" $((i+1)) "${choices[i]:- }" "${HOSTTAB[i]}"
    printf "%3d%s) %-10s\n" $((i+1)) "${choices[i]:- }" "${HOSTTAB[i]}"
done

I need to split this all 100 items in severals columns:

  1 ) ITEM1
  2 ) ITEM2
  3 ) ITEM3
  4 ) ITEM4
  5 ) ITEM5
until
 98  ) ITEM98
 99  ) ITEM99
 100 ) ITEM100

Thanks for any help.

Regards,

You may use this awk :

awk -v n=5 '{
ORS = (NR % n ? "\t" : "\n"); $1 = sprintf("%02d ) %s", NR, $1)} 1' file

01 ) item1  02 ) item2  03 ) item3  04 ) item4  05 ) item5
06 ) item6  07 ) item7  08 ) item8  09 ) item9  10 ) item10
11 ) item11 12 ) item12 13 ) item13 14 ) item14 15 ) item15
16 ) item16 17 ) item17 18 ) item18 19 ) item19 20 ) item20
21 ) item21 22 ) item22 23 ) item23 24 ) item24 25 ) item25

In the awk command, you can pass n=20 to print 20 columns per line or n=30 to get 30 columns per line.

I found an other method with the loop with | column.

I share it:

for i in ${!HOSTTAB[@]}; do
    printf "%3d%s) %s\n" $((i+1)) "${choices[i]:- }" "${HOSTTAB[i]}"
    echo ""
done | column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM