1

I have a command which generates colored output. I wish to grep the plain text of that command (while still preserving the color) for brackets. If I grep -F '[', every line matches, due to the color codes.

How can I grep for brackets (or other plain text features) without losing the color?

Note: There are similar posts about grepping the color codes, or preserving the color, neither of which help here.

1
  • 1
    You need to search for a longer pattern, something that excludes the color escapes while passing what you are looking for. Without having any idea of what you are looking for, we can't guess.
    – user10489
    Jan 2, 2022 at 17:19

1 Answer 1

0

You can do something like that:

$ printf "1st line \033[31m RED literal [ \033[0m NORMAL \n2nd line \033[31m RED \033[0m NORMAL \n" | while IFS=; read -r line
do
    if echo "$line" | ansifilter | grep -F '[' >/dev/null
    then
        echo "$line"
    fi
done
1st line  RED literal [  NORMAL

You have to have ansifilter installed.

Notice that is not very effective because grep is called on every line but it should work fine for small inputs.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .