BASH输出列格式

aLe*_*788 7 bash formatting

第一次发帖.你好,世界.处理我的第一个脚本,只是检查我的网站列表是否在线,然后返回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"
Run Code Online (Sandbox Code Playgroud)

以下列格式输出

google.com              200 0.389
facebook.com                200 0.511
abnormallyLongDomain.com                200 0.786
Run Code Online (Sandbox Code Playgroud)

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

DOMAIN_NAME                 HTTP_CODE   RESPONSE_TIME
google.com                  200         0.389
facebook.com                200         0.511
abnormallyLongDomain.com    200         0.486
Run Code Online (Sandbox Code Playgroud)

谢谢大家的帮助!!

Joh*_*024 7

column是非常好的.但是,您已经在使用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"
Run Code Online (Sandbox Code Playgroud)

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

DOMAIN_NAME              HTTP_CODE   RESPONSE_TIME
google.com               301         0.305
facebook.com             301         0.415
abnormallyLongDomain.com 000         0.000
Run Code Online (Sandbox Code Playgroud)

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

进一步改进

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

#!/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"
Run Code Online (Sandbox Code Playgroud)

或者,正如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"
Run Code Online (Sandbox Code Playgroud)

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