代码是:
#!/bin/bash
ips[0]='192.168.0.1'
ips[1]='192.168.0'
ips[2]='255.255.255.256'
ips[3]='123.123.123.123.123'
ips[4]='a.b.c.d'
ips[5]='255.255.255.255'
ips[6]='0.0.0.0'
ips[7]='192.168.1.1'
ips[8]='4.2.2.2'
regex="^((25[0-5]|2[0-4][0-9]|[01][0-9][0-9]|[0-9]{1,2})[.]){3}(25[0-5]|2[0-4][0-9]|[01][0-9][0-9]|[0-9]{1,2})$"
regexVar=$(printf "\033[33mSaved in a VARIABLE\033[0m")
regexStr=$(printf "\033[34mIs a STRING\033[0m")
validOut=$(printf "\033[32mValid\033[0m")
invalidOut=$(printf "\033[31mInvalid\033[0m")
noQuotes="NO quotes"
singleQuotes="Single quotes"
doubleQuotes="Double quotes"
printStyle="%-25s %-10s %-20s %-10s\n"
printTitle=$(printf "${printStyle}" "IP Address" "Validity" "Regex" "Quote Type")
print2ndLine=$(printf "${printStyle}" "====================" "==========" "====================" "==========")
function validIP1a() {
echo "${printTitle}"
echo "${print2ndLine}"
for (( i=0; i<${#ips[@]}; i++ )); do
if [[ "${ips[i]}" =~ $regex ]]; then
printf "${printStyle}" "${ips[i]}" "${validOut}" "${regexVar}" "${noQuotes}"
else
printf "${printStyle}" "${ips[i]}" "${invalidOut}" "${regexVar}" "${noQuotes}"
fi
done
}
validIP1a
输出是:
预期输出是:
为什么我无法得到预期的结果?怎么解决呢?
答案1
因为printf
统计了设置颜色的转义码中的字符;它不知道它们实际上并没有打印。您需要将它们放在固定长度格式化 ( %-20s
) 字符串之外。在这里比较两个printf
:
#!/bin/bash
green=$'\033[32m'
yellow=$'\033[33m'
normal=$'\033[0m'
printf "1234567890123456789012345678901234567\n";
printf "%-20s %s\n" "${yellow}some string${normal}" "next col"
printf "${yellow}%-20s${normal} %s\n" "some string" "next col"
输出应如下所示:
当然,如果颜色可以改变,我们可以把它放在另一个变量中:
printf "%s%-20s${normal} %s\n" "$green" "some string" "next col"
答案2
您可能想要计算validOut
和中的字符数invalidOut
;我数了数,每一个都超过10个:
# 11 11111
# 1 2245678901 23456
validOut=$(printf "\033[32mValid\033[0m")
invalidOut=$(printf "\033[31mInvalid\033[0m")
请记住,穷人printf
不可能知道其中一些字符是不可见的并会改变颜色...您请求一个至少包含 10 个字符的左对齐字段,然后继续用超过 10 个字符的字符串填充它;难怪结果不是垂直对齐的。