CodingBear
CodingBear
Published on 2026-02-05 / 2 Visits
0
0

When ANSI Color Escape Sequences Break awk Matching

The issue started when I was using awk to match the output of ip link, but a single space stubbornly refused to match.

$ ip -o link show
......
13: ztrfydqpmi: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 2800 qdisc fq_codel state UNKNOWN mode DEFAULT group default qlen 1000\    link/ether 02:02:48:ab:4b:a4 brd ff:ff:ff:ff:ff:ff

$ ip -o link show | awk -F': ' '/^([0-9]+): zt/ {print $2; exit}' # Shows nothing

$ ip -o link show | awk -F': ' '/13: z/ {print $0}' # Still shows nothing

$ ip -o link show | awk -F': ' '/13:/ {print $0}'
13: ztrfydqpmi: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 2800 qdisc fq_codel state UNKNOWN mode DEFAULT group default qlen 1000\    link/ether 02:02:48:ab:4b:a4 brd ff:ff:ff:ff:ff:ff

By comparison, it became clear that the space itself was not being matched. After a hint from ChatGPT, I suspected there might be invisible characters involved.

# Use sed -n 'l' to make invisible characters explicit
ip -o link show | grep '^13:' | sed -n 'l'
13: \033[1;36mztrfydqpmi: \033[0m<BROADCAST,MULTICAST,UP,LOWER_UP> mt\
u 2800 qdisc fq_codel state UNKNOWN mode DEFAULT group default qlen 1\
000\\    link/ether \033[1;33m02:02:48:ab:4b:a4\033[0m brd \033[1;33m\
ff:ff:ff:ff:ff:ff\033[0m$

This revealed extra \033[1;36m ANSI color escape sequences in the output. With these sequences inserted between the : and the ASCII space, the pattern naturally failed to match.

As expected, using ip -o -color=never link show produced clean output and the awk matching worked normally.

Checking which ip showed:

ip: aliased to ip -c

That turned out to be the root cause. Changing the alias to use -c=auto fixed the issue.

Conclusion: never use colored output in pipelines.

Related discussion:


Comment