微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

BASH输出列格式

第一次发帖.你好,世界.处理我的第一个脚本,只是检查我的网站列表是否在线,然后返回HTTP代码以及将其返回到桌面上另一个文件所花费的时间.

– 这篇文章将在MAC OSX上运行 –

我想修改我的脚本,以便将其输出格式化为3个整齐的列.

目前

#!/bin/bash
file="/Users/USER12/Desktop/url-list.txt"
printf "" > /Users/USER12/Desktop/url-results.txt
while read line
do
    printf "$line" >> /Users/USER12/Desktop/url-results.txt
    printf "\t\t\t\t" >> /Users/USER12/Desktop/url-results.txt
    curl -o /dev/null --silent --head --write-out '%{http_code} %{time_total}' "$line" >> /Users/USER12/Desktop/url-results.txt
    printf "\n" >> /Users/USER12/Desktop/url-results.txt
done <"$file"

以下列格式输出

google.com              200 0.389
facebook.com                200 0.511
abnormallyLongDomain.com                200 0.786

但我想格式化为整齐的对齐列,以便于阅读

DOMAIN_NAME                 HTTP_CODE   RESPONSE_TIME
google.com                  200         0.389
facebook.com                200         0.511
abnormallyLongDomain.com    200         0.486

谢谢大家的帮助!!

专栏非常好.但是,您已经在使用printf,它可以很好地控制输出格式.使用printf的功能还可以使代码有所简化:
#!/bin/bash
file="/Users/USER12/Desktop/url-list.txt"
log="/Users/USER12/Desktop/url-results.txt"
fmt="%-25s%-12s%-12s\n"
printf "$fmt" DOMAIN_NAME HTTP_CODE RESPONSE_TIME > "$log"
while read line
do
    read code time < <(curl -o /dev/null --silent --head --write-out '%{http_code} %{time_total}' "$line")
    printf "$fmt" "$line" "$code" "$time" >> "$log"
done <"$file"

使用上面定义的格式,输出看起来像:

DOMAIN_NAME              HTTP_CODE   RESPONSE_TIME
google.com               301         0.305
facebook.com             301         0.415
abnormallyLongDomain.com 000         0.000

您可以通过更改脚本中的fmt变量来微调输出格式,例如间距或对齐.

进一步改进

上面的代码用每个循环打开和关闭日志文件.这可以像Charles Duffy建议的那样避免,只需使用exec在第一个printf语句之前将stdout重定向到日志文件

#!/bin/bash
file="/Users/USER12/Desktop/url-list.txt"
exec >"/Users/USER12/Desktop/url-results.txt"
fmt="%-25s%-12s%-12s\n"
printf "$fmt" DOMAIN_NAME HTTP_CODE RESPONSE_TIME
while read line
do
    read code time < <(curl -o /dev/null --silent --head --write-out '%{http_code} %{time_total}' "$line")
    printf "$fmt" "$line" "$code" "$time"
done <"$file"

或者,正如Chepner建议的那样,可以将打印语句分组:

#!/bin/bash
file="/Users/USER12/Desktop/url-list.txt"
fmt="%-25s%-12s%-12s\n"
{
printf "$fmt" DOMAIN_NAME HTTP_CODE RESPONSE_TIME
while read line
do
    read code time < <(curl -o /dev/null --silent --head --write-out '%{http_code} %{time_total}' "$line")
    printf "$fmt" "$line" "$code" "$time"
done <"$file"
} >"/Users/USER12/Desktop/url-results.txt"

分组的一个优点是,在组之后,stdout会自动恢复到正常值.

原文地址:https://www.jb51.cc/bash/383570.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐