I have a file (file.txt) like this:
Yes
Yes
No
No
and I want to output this file to a bash terminal with "Yes" as green and "No" as red. I have written the following script:
RED='\033[0;31m'
NC='\033[0m'
GREEN='\033[0;32m'
cat file.txt | sed 's/No/${RED}No${NC}/g' | sed 's/Yes/${GREEN}Yes${NC}/g' > color_file.txt
printf "$(cat color_file.txt)"
The output looks like this:
${GREEN}Yes${NC}
${GREEN}Yes${NC}
${RED}No${NC}
${RED}No${NC}
Instead of being colored.
The coloring works if I have a script like:
RED='\033[0;31m'
printf "${RED}No${NC}"
How would I read a file, color its contents and then print to the terminal?
You could leave the expansions in the file and replace the
${...}forms with the variables when reading the file:But I believe you wanted to actually output the escape sequences into the file:
Or maybe you wanted
printfto interpret the escpe sequences in the content of a file:Check your scripts with shellcheck - it will tell you about all mistakes that you did.
Variable expansion does not expand within single quotes.
seddoes not interpret octal escape sequences. Forsedthe string\033is a zero byte 0x00 followed by two33.Is an antipattern. Just execute
cat ....Is a useless use of cat.
It is not possible to read a file with
printf. It's not a tool for that.This feels unrelated to your issue, but to execute a file just call it with an interpreter
sh ./file.shor source it within current execution environment. ./file.sh.