How do I capture/escape #
in a test
? I'm trying to use the clever answer from How to reference captures in bash regex replacement to color everything after a #
green
foo='hello # world'
foo="$([[ $foo =~ (#.*) ]] && echo -e ${foo/$BASH_REMATCH/\\e[32m${BASH_REMATCH[1]}\\e[0m} || echo $foo)"
echo -e $foo
I have tried using (#.*)
, (\#.*)
, and (\\#.*)
. The first two apparently successfully test hello # world
, but don't replace it correctly...?
[[ $foo =~ (#.+) ]] && echo -e "${foo/$BASH_REMATCH/! ${BASH_REMATCH[1]} !}"
# prints: hello # world
[[ $foo =~ ( #.+) ]] && echo -e "${foo/$BASH_REMATCH/! ${BASH_REMATCH[1]} !}"
# prints: hello! # world !
As seen above, if I precede the #
with a space, it works fine, but I want a generic solution, and lookbehinds don't appear to work.
I can get this to work using sed, but for my purposes, it's very slow (on the order of seconds). I'm sure there's a faster way that I could do this using sed, but I'd really like a vanilla bash solution.