加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

BASH输出列格式

发布时间:2020-12-16 01:37:55 所属栏目:安全 来源:网络整理
导读:第一次发帖.你好,世界.处理我的第一个脚本,只是检查我的网站列表是否在线,然后返回HTTP代码以及将其返回到桌面上另一个文件所花费的时间. – 这篇文章将在MAC OSX上运行 – 我想修改我的脚本,以便将其输出格式化为3个整齐的列. 目前 #!/bin/bashfile="/Users
第一次发帖.你好,世界.处理我的第一个脚本,只是检查我的网站列表是否在线,然后返回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 "tttt" >> /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%-12sn"
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%-12sn"
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%-12sn"
{
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会自动恢复到正常值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读