我刚刚在其他人的帮助下制作了我的第一个 shell 脚本,它按预期工作,但我想更多地组织它。
当前脚本:
{ date '+%F %T';
"$ipath"/cli iedge list |
awk 'BEGIN { print "Registration ID", "Ongoing Calls"}
/Registration ID/ { id = $3; next }
/Ongoing Calls/ { print id,$3 }'
} >> "$ifile"
其输出:
- Registration ID Ongoing Calls
- Nitin_03 30
- Nitin_01 0
相反,我希望输出格式如下:
-------------------------------------
|Registration ID | Ongoing Calls |
-------------------------------------
| Nitin_03 | 30 |
-------------------------------------
| Nitin_01 | 0 |
-------------------------------------
我该怎么做呢?我尝试了以下方法,它大部分有效,但是当我添加另一个“字符”时,我遇到了致命错误。
ipath=/usr/local/nextone/bin
ifile=/root/Nick.csv
"$ipath"/cli igrp list | awk '
BEGIN { print "------------------------------------";
printf "|%-17s|%-16s|%-15s|\n","Iedge Group", "maxCallsIn"
"maxCallsOut"
}
/Iedge Group/ { id = $3; next }
/maxCallsIn/
/maxCallsOut/{print "------------------------------------"; printf
"|%-17s|%-16s|%-15s\n",id,$3 }
END{
print "------------------------------------";
}'
当我添加以下内容时,我开始收到此错误maxCallsOut
:
awk: cmd. line:3: fatal: not enough arguments to satisfy format string
`|%-17s|%-16s|%-15s|
'
^ ran out for this one
答案1
要从 awk 获取格式化输出,请使用printf
:
$ "$ipath"/cli iedge list | awk 'BEGIN { print "------------------------------------"; printf "|%-17s|%-16s|\n","Registration ID", "Ongoing Calls"} /Registration ID/ { id = $3; next } /Ongoing Calls/ {print "------------------------------------"; printf "|%-17s|%-16s|\n",id,$3 } END{print "------------------------------------";}'
------------------------------------
|Registration ID |Ongoing Calls |
------------------------------------
|Nitin_03 |30 |
------------------------------------
|Nitin_01 |0 |
------------------------------------
如果更容易阅读,以下内容是相同的,但分布在脚本中的多行中:
#!/bin/sh
"$ipath"/cli iedge list | awk '
BEGIN { print "------------------------------------";
printf "|%-17s|%-16s|\n","Registration ID", "Ongoing Calls"
}
/Registration ID/ { id = $3; next }
/Ongoing Calls/ {print "------------------------------------"; printf "|%-17s|%-16s|\n",id,$3 }
END{
print "------------------------------------";
}
'
printf
可以调整报表以获得您喜欢的任何格式。