我正在尝试从格式化为表格的文件中打印信息。我到目前为止
BEGIN {
OFS = "\t";
FS = ":";
print "\t\t----Employee Information---- ";
printf("%s %40s %20s %4s %8s %4s %15s \n", "NAME", "TELEPHONE", "AGE", "|", "Salary", "|", "License No.")
}
{ printf ("%s %30s %30s %30s %30s\n", $4, $1, $5, $2, $3) }
它负责处理列,但我似乎无法按照我的意愿排列数据。
这是我必须输出的数据示例:
{246} 548-1278:2500:175A106:Miss Cherise Hilton-Moore : 30
{408} 538-2358:1550:201B154:Mr Reynold Watson :37
{210} 655-6279:2600:509UYT6:Miss Natalie Judy-Sealy :32
{210} 548-1348:2500:175XCVD3:Mr John McCollin : 26
{208} 548-1278:1880:150P9URE:Mr Ronald Francis: 31
按顺序有区号、电话号码、工资、执照号码、姓名、年龄。我希望将其排列在列下:
Name Telephone Age Salary License Number.
但我得到的输出如下所示:
NAME TELEPHONE AGE | Salary | License No.
Miss Cherise Hilton-Moore {246} 548-1278 30 2500 175A106
Mr Reynold Watson {408} 538-2358 37 1550 201B154
Miss Natalie Judy-Sealy {210} 655-6279 32 2600 509UYT6
编辑:首先,感谢大家的指导。这是我到目前为止所拥有的:
BEGIN {FS = ":";
print "\t\t----Employee Information---- ";
printf("%s %40s %20s %4s %8s %4s %15s \n", "NAME", "TELEPHONE", "AGE", "|", "Salary", "|", "License No.")}\
{printf ("%-35s %-26s %-10s %-15s %-10s\n", $4, $1, $5, $2, $3)}
#End of Script
它不会说它在一般情况下有效。我会继续寻找,但是,这是基于我对说明符的理解。
答案1
$ cat tst.awk
BEGIN {
ARGV[ARGC] = ARGV[ARGC-1] # So we can read the input twice, first to get the max field widths.
ARGC++
# Not using character class [:blank:] because nawk does not support character classes
FS = "[ \t]*:[ \t]*"
split("TELEPHONE:SALARY:LICENSE NO.:NAME:AGE",inNr2Name)
for (inNr in inNr2Name) {
name = inNr2Name[inNr]
wid = length(name)
name2wid[name] = wid
f[name] = inNr # field name to input field number
}
print "\t\t----Employee Information---- "
}
NR==FNR {
for (inNr=1; inNr<=NF; inNr++) {
name = inNr2Name[inNr]
val = $inNr
wid = length(val)
name2wid[name] = (name2wid[name] > wid ? name2wid[name] : wid)
}
next
}
FNR == 1 {
outFmt = "%-" name2wid["NAME"] "s " \
"%-" name2wid["TELEPHONE"] "s " \
"%-" name2wid["AGE"] "s " \
"| " \
"%-" name2wid["SALARY"] "s " \
"| " \
"%-" name2wid["LICENSE NO."] "s\n"
printf outFmt, "NAME", "TELEPHONE", "AGE", "SALARY", "LICENSE NO."
}
{
printf outFmt, $(f["NAME"]), $(f["TELEPHONE"]), $(f["AGE"]), $(f["SALARY"]), $(f["LICENSE NO."])
}
$ awk -f tst.awk file
----Employee Information----
NAME TELEPHONE AGE | SALARY | LICENSE NO.
Miss Cherise Hilton-Moore {246} 548-1278 30 | 2500 | 175A106
Mr Reynold Watson {408} 538-2358 37 | 1550 | 201B154
Miss Natalie Judy-Sealy {210} 655-6279 32 | 2600 | 509UYT6
Mr John McCollin {210} 548-1348 26 | 2500 | 175XCVD3
Mr Ronald Francis {208} 548-1278 31 | 1880 | 150P9URE
我使用了很多中间变量,所有变量都有有意义的名称,所以我希望您经过一番思考并查看手册页后能够理解它的作用,但如果没有,请随时提出问题。