How would I go about colorizing the output of
echo "`tput setaf 1`foo`tput op`" works as expected
echo "foo" | sed -e 's/(foo)/`tput setaf 1`\0`tput op`/g' however, does not.
What am I missing here?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
The backticks `` in the echo command spawn a process and it's output is substituted into the echo command line. You can see this with e.g.
echo "`tput setaf 1`" | hexdump -C 00000000 1b 5b 33 31 6d 0a |.[31m.|
This works because the contents of the
"..." are expanded before being passed to echo.
The sed command you're using wraps everything in
' so it is passed to sed without expansion and sed sees it all as literal text.
You can fix this by putting "" around your sed command
echo "foo" | sed -e "s/\(foo\)/`tput setaf 1`\1`tput op`/g"
You also had an error in your sed command. The
) need to be escaped
\) to denote the remembered pattern. I've also never use
\0 I've always used
\1 as the first remembered pattern.
Does it have to be
echo "foo bar baz" | grep --color=auto "bar"
The above will highlight
bar in red by default. The man page says you can choose what colour to use with the environment variable
To make it print all lines and only highlight
echo "foo bar baz" | grep -E --color=auto "^|bar"