Text-Formatting

將輸出列印到 3 個單獨的列

  • January 30, 2022
MYPATH=/var/www/html/error_logs/
TOTALFILE=$(ls $MYPATH* | wc -l)
FILETIME=$(stat --format=%y $MYPATH* | head -5 | cut -d'.' -f1)  
FILE=$(ls -1tcr $MYPATH* | head -5 | rev | cut -d/ -f1 | rev)
TOPLINE=$(head -1 $MYPATH* | grep -Po '".*?"' | head -5)

如何優雅地將這 5 個資訊文件列印到帶有標題的列中?

FILE CREATED TIME   | FILE NAME        | ERROR HEADER
---------------------------------------------
$FILETIME           | $FILE            | $TOPLINE
2012-11-29 11:27:45 | 684939947465     | "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)"

依此類推,所有 5 個文件。

total files: $TOTALFILE

有什麼簡單的方法可以得到我想要的嗎?

這是我回顯每個變數時得到的輸出:

2012-11-29 11:27:45 2012-11-29 11:27:41 2012-11-28 23:33:01 2012-11-26 10:23:37 2012-11-19 22:49:36
684939947465 1313307654813 1311411049509 1234980770182 354797376843
"SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)" "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)" "Connection to localhost:6379 failed: Connection refused (111)" "An error occurred connecting to Redis." "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)"

您可以使用columnLinux上屬於util-linux軟體包的命令。它也可以在FreeBSDNetBSDOpenBSDDragonFly BSD上使用。

將此與循環結合起來,您就可以開展業務,例如:

#!/bin/sh

MYPATH=/
TOTALFILE=$(ls $MYPATH/* | wc -l)
FILE=$(ls -1tcr $MYPATH/* | head -5 | rev | cut -d/ -f1 | rev)

declare -a FILES
declare -a FILETIME

OUTPUT="FILENAME CREATED TIME ERROR_HEADER\n\n------------------------------ ----------------------------- ----------------------------------- ------$"

for i in $MYPATH/*;
do
   FILES[${#FILES[@]}]="$i"
   FILETIME[${#FILETIME[@]}]=$(stat --format=%y $i | head -5 | cut -d'.' -f1)
   TOPLINE=$(head -1 $i | grep -Po '".*?"' | head -5)

   OUTPUT="$OUTPUT\n${FILES[${#FILES[@]}-1]} ${FILETIME[${#FILETIME[@]}-1]} $TOPLINE\n"
done

echo -ne $OUTPUT | column -t

我建議使用printf,例如:

printf "%-30s | %-30s | %-30s" "$FILETIME" "$FILE" "$TOPLINE"

where%-30s 表示為 string 類型的輸入參數保留 30 個字元。-表示左對齊。

引用自:https://unix.stackexchange.com/questions/59249