我编写了一个脚本,显示用户的姓名和部门,并且该脚本有效。此外,我正在尝试绘制一条分隔线,并根据需要将名称标题分配给列。我正在尝试用 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
我正在尝试找到一种方法,在输出显示如下预期之前用标题画一条线:
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: [email protected]
Phone: 09999999999
Internal #:
Ext: 4848
Cell: 8777880559
Fax: -
Building: NOIDA 03
Floor: 03
Room: 3.3.109
答案1
你有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