3

The code is:

#!/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

The output is:

output can't be aligned

The expected output is:

expected aligned output

Why I can't get the expected result? How to solve it?

3

Because printf counts the characters in the escape code that sets the color; it doesn't know they don't actually print. You'd need to put them outside the fixed-length formatted (%-20s) strings. Compare the two printfs here:

#!/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"

The output should look like this:

sample output

Of course, if the color can change, we can put it in another variable:

printf "%s%-20s${normal} %s\n" "$green" "some string"  "next col"
2

You may want to count the characters in validOut and invalidOut; I count more than 10 in each of them:

#                                11   11111
#                    1   2245678901   23456
  validOut=$(printf "\033[32mValid\033[0m")
invalidOut=$(printf "\033[31mInvalid\033[0m")

Remember that poor printf cannot possibly know that some of those characters are invisible and make color changes... You requested a left-aligned field of at least 10 characters, and then proceeded to fill it with strings having more than 10 characters; no wonder the result is not vertically aligned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.