在bash中创建动态表

时间:2017-10-04 12:59:59

标签: bash awk sed

我有bash脚本,可以创建不同的用户和密码。密码和用户存储在变量中。

    cat << EOT
+---------------------------------------+
| Linux Logins                          |
+---------------+-----------------------+
| User          | Password              |
+---------------+-----------------------+
| $test      | $testpw               |
+---------------+-----------------------+

EOT

问题在于,根据存储变量的长度,表格会像这样搞乱:

+---------------------------------------+
| Linux Logins                          |
+---------------+-----------------------+
| User          | Password              |
+---------------+-----------------------+
| michael         | helolopk8712t76               |
+---------------+-----------------------+

这是因为标签是硬编码的。我怎样才能以不同的方式解决这个问题?我知道有awk和专栏这样做。 如果可能的话,我希望它在mysql控制台中是动态的。

3 个答案:

答案 0 :(得分:2)

我认为您的意思是说您的问题是由于您的标签是硬编码的。但是标签不够灵活,无法做到你想要的。你可以这样做:

cat << EOT            
+---------------------------------------+              
| Linux Logins                          |              
+---------------+-----------------------+              
| User          | Password              |              
+---------------+-----------------------+              
| $(printf %-14s "$test")| $(printf %-22s "$testpw")|          
+---------------+-----------------------+              

EOT

答案 1 :(得分:1)

变量可以用printf填充

printf -v test   %20s "$test"
printf -v testpw %20s "$testpw"

或左对齐

printf -v test   %-20s "$test"
printf -v testpw %-20s "$testpw"

或特定长度后的截断(19)

printf -v test   %-20.19s "$test"
printf -v testpw %-20.19s "$testpw"

答案 2 :(得分:0)

很好的答案。如果它对任何人有用,我的表格会分配颜色并右对齐值。使用:创建一个文件,例如table.sh,设置权限 chmod u+x table.sh 并运行文件 ./table.sh

#!/usr/bin/env bash

# Define colours
CYAN='\033[0;36m' 
GREEN='\033[0;32m' 
LIGHTRED='\033[1;31m' 
MAGENTA='\033[1;35m'
NC='\033[0m' # No Colour 
YELLOW='\033[1;33m' 

# Hard code variable values for this POC 
critical=0
high=2
medium=12
low=112
notScanned=10
total=136

# Print table with values right-aligned & colour-coded 

echo
printf "${NC}+--------------------------------+\n"
printf "${NC}|  ECR Vulnerabilities           |\n"
printf "${NC}+--------------------------------+\n"
printf "${NC}|  Critical      |${LIGHTRED} $(printf '%8.5s\n' ${critical})${NC}      |\n"
printf "${NC}+--------------------------------+\n"
printf "${NC}|  High          |${MAGENTA} $(printf '%8.5s\n' ${high})${NC}      |\n"
printf "${NC}+--------------------------------+\n"
printf "${NC}|  Medium        |${YELLOW} $(printf '%8.5s\n' ${medium})${NC}      |\n"
printf "${NC}+--------------------------------+\n"
printf "${NC}|  Low           |${CYAN} $(printf '%8.5s\n' ${low})${NC}      |\n"
printf "${NC}+--------------------------------+\n"
printf "${NC}|  Not Scanned   |${NC} $(printf '%8.5s\n' ${notScanned})${NC}      |\n"
printf "${NC}+--------------------------------+\n"
printf "${NC}|  Total         |${GREEN} $(printf '%8.5s\n' ${total})${NC}      |\n"
printf "${NC}+--------------------------------+\n"