Format output in columns

后端 未结 5 2248
慢半拍i
慢半拍i 2020-12-16 19:22

I was wondering how to format the following output:

-0.3116274D-04
-0.2389361D-04
-0.1192458D-04
0.3306203D-04
0.2534987D-04
0.1265136D-04
-0.2167920D-04
-0.         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 19:51

    Wow, haven't seen this in a while. There are several ways:

    The ol' pr command was used for this type of work -- especially if you wanted those columns going vertically instead of horizontally.

    However, I would use printf which allows me to keep the text a constant width, and then use a counter and the modulo operator to count when I have five items in a line. The modulo operator is sometimes called a remainder operator. However, it functions like a clock:

    #!/bin/bash
    # 
    
    count=0
    while read number
    do
        ((count+=1))
        printf "%14.14s  " $number
        if ((count % 5 == 0))
        then
            printf "\n"
        fi
    done < $file
    printf "\n"
    

    The format for the printf is missing the minus ( i.e. %-14.14s) which forces the text to be aligned to the right instead of the left. That way the minus doesn't throw me off.

提交回复
热议问题