help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Colour certain parts of a string


From: Greg Wooledge
Subject: Re: Colour certain parts of a string
Date: Mon, 20 Mar 2023 10:06:32 -0400

On Mon, Mar 20, 2023 at 01:40:35PM +0000, uzibalqa wrote:
> I would like to take a string and colour certain parts by calling a function 
> named "glow".
> 
> For instance, the following would colour the square brackets in blue whilst 
> keeping the 
> rest at the default terminal colour.
> 
> glow "[" "]" $str 

I'll assume you mean "print the final argument to stdout, while adding
color codes for any character which matches any of the other arguments".

glow() {
    local blue=$(tput setaf 4)
    local norm=$(tput sgr0)
    local -A glowchar
    local str c i

    # Iterate over non-final arguments, and record them in our lookup table.
    while (($# > 1)); do
        glowchar[$1]=1
        shift
    done

    # Print the remaining argument, character by character, adding color.
    str=$1
    for ((i=0; i < ${#str}; i++)); do
        c=${str:i:1}
        if [[ ${glowchar[$c]} ]]; then
            printf %s%s%s "$blue" "$c" "$norm"
        else
            printf %s "$c"
        fi
    done

    echo
}

Also, you need to quote "$str" when you pass it.  You DON'T need to quote
the [ and ] characters, but it doesn't hurt.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]