maro
maro

Reputation: 503

How to change the output color without using echo?

Is it possible to change the output color without using echo? Something like "set color to yellow".

I have a script

#!/bin/bash
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e ${YELLOW}
cat file.txt | awk 'NR==1 { print $0; }'
echo -e ${BLUE}
cat file.txt | awk 'NR==2 { print $0; }'
echo -e ${NC}

which prints the first line of file.txt in yellow and the second line in blue. But it also adds extra lines in the places where I have "echo" commands.

I tried something like this:

#!/bin/bash
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

${YELLOW} cat file.txt | awk 'NR==1 { print $0; }'
${BLUE} cat file.txt | awk 'NR==2 { print $0; }' ${NC}

But it doesn't work because "echo" command needs -e parameter to display colors.

So my question is: Can I change the output color without using echo? If not, how to remove these extra lines between lines of the file? Is it possible to correct this script to not generate extra lines?

Current output:

 
first line of file.txt

second line of file.txt
 

Desirable output:

first line of file.txt
second line of file.txt

Upvotes: 1

Views: 2158

Answers (3)

that other guy
that other guy

Reputation: 123410

Use tput:

#!/bin/bash

yellow() { tput setaf 3; }
blue() { tput setaf 4; }
nc() { tput sgr0; }

[[ -t 1 ]] || export TERM=dumb

yellow
cat file.txt | awk 'NR==1 { print $0; }'
blue
cat file.txt | awk 'NR==2 { print $0; }'
nc

That way you don't have to hard code terminal codes, and the terminal type and capabilities will be respected. For example, if you're using a terminal that doesn't support colors, you'll get uncolored text instead of garbage.

Here, that same feature is used to get uncolored text when stdout is not a terminal, which is the canonical Unix behavior to avoid problems when piping to other programs.

Upvotes: 2

Bach Lien
Bach Lien

Reputation: 1060

 echo -e -n "$YELLOW"

-n: not add extra newline

Upvotes: 2

iamauser
iamauser

Reputation: 11469

Use printf.

 printf '\e[1;34m%-6s\e[m' "First line of text in BLUE"
 printf '\e[1;31m%-6s\n\e[m' "Second line of text in RED WITH A NEW LINE"

Here is a tiny bash function to do this:

$ cat col.sh
#!/bin/bash

colprint()
{
    printf '\e[1;%dm%-6s\n\e[m' "$1" "$2"
}

# For your input file.
colprint 31 "$(awk 'NR==1{print;}' file.txt)"
colprint 34 "$(awk 'NR==2{print;}' file.txt)"
colprint 33 "$(awk 'NR==3{print;}' file.txt)"

Output in colors of course on a xterm with colors.

Upvotes: 3

Related Questions