Printf

如何在輸出顯示之前繪製帶有名稱標題的分隔線

  • January 19, 2017

我已經編寫了一個腳本,它顯示使用者的姓名和部門並且可以工作。此外,我正在嘗試繪製一條分隔線,並將名稱標題分配給需要的列。我正在嘗試用 printf 來做,但不知何故現在無法得到它..任何幫助將不勝感激..

以下是腳本和預期結果..

#!/bin/sh
for names in `cat namefile`;

do

DATA1="`/grid/common/bin/cod -u $names | awk -F: '/Department/ {print $2}'`"
DATA2="`/grid/common/bin/cod -u $names | awk -F: '/Name/ {print $2}'`"

#printf '%*s\n' "${COLUMN'S:-$(tput cols)}" '' | tr ' ' -
printf "%-50s : %10s\n" "$DATA2" "$DATA1"
done
bash-4.1$ sh Userdetail.sh
       Karn Kumar                                 :   TT, Infra, VM & India
       Manas .                                    :   TT, Infra, VM & India
       Pranjal Agrawal                            :   TT, Infra, VM & India
       Rogen Mana                                 :   PP OPS-Brazil

我正在嘗試找到一種方法,在輸出顯示如下預期之前用 Titles 畫一條線:

 Name                                         Department


Karn Kumar                                 :   TT, Infra, VM & India
Manas .                                    :   TT, Infra, VM & India
Pranjal Agrawal                            :   TT, Infra, VM & India
Rogen Mana                                 :   PP OPS-Brazil

只是為了更多地了解命令部分..

bash-4.1$ /grid/common/bin/cod -u karn
       Name:        Karn Kumar
       Title:       IT -Staff Systems Engineer

       Department:  TT, Infra, VM & India
       Mgr:         KK LIN
       Mgr Login:   ttlin
       E-Mail:      karn@abc.com
       Phone:       09999999999
       Internal #:  
       Ext:         4848
       Cell:        8777880559
       Fax:            -
       Building:    NOIDA 03
       Floor:       03
       Room:        3.3.109

你有printf "%-50s : %10s\n" "$DATA2" "$DATA1",這告訴我你總共將有 63 個字元寬的行(包括空格和:)。因此,我們將要printf "%63s"字元串。簡單的方法是列印空格,然後將它們全部轉換為-這樣

printf "%60s" " " | tr ' ' '-' 

我們當然可以使用更簡單的方法,但它是特定於bash. 但是,我們可以稍微修改一下:

printf "=%.0s"  $(seq 1 63)

這將適用於任何已seq安裝的 shell 和系統。

因此,在進入循環之前列印標題。例如,這是一個非常簡單的案例:

$ cat ./print_header.sh                                                                                           
#!/bin/bash
# print header
printf "%-50s : %10s\n" "Name"  "Department"
# print separator
printf "=%.0s"  $(seq 1 63)
# insert a newline
printf "\n"
# and this is where your for loop would begin.
# just for the sake of example, there's only one line
printf "%-50s : %10s\n" "John Doe"  "IT,Infra"
$ ./print_header.sh                                                                                               
Name                                               : Department
===============================================================
John Doe                                           :   IT,Infra

引用自:https://unix.stackexchange.com/questions/338527