aquib nawaz
aquib nawaz

Reputation: 89

Using awk to color the output in bash

I have two files.
First one is csv while other one is plain text file.
I want to print all the lines of file2 which contains column 1 of first file with font color column2 and background color column3.
for example:
f1 contains

Basic Engineering,BLACK,WHITE
Science,RED,BLUE

f2 contains with field width of 20 each:

foo      abc            Science   AA 
bar      cde  Basic Engineering   AP 
baz     efgh            Science   AB

expected output:

foo      abc            Science   AA (Red font, Blue background)
bar      cde  Basic Engineering   AP (Black font, White background) 
baz     efgh            Science   AB (Red font, Blue background)

I have already defined color in a seperate file defineColors.sh as:

BLACK_FONT=`tput setaf 0`
RED_FONT=`tput setaf 1`
WHITE_BACKGROUND=`tput setab 7`
BLUE_BACKGROUND=`tput setab 4`
RESET_ALL=`tput sgr0`

My try :

awk -F, '{sed "/$1/p" f2 | sed -e 's/^\(.*\)$/'"$2_FONT"''"$3_BACKGROUND"'\1/' }' f1

Upvotes: 2

Views: 876

Answers (1)

Ed Morton
Ed Morton

Reputation: 203368

$ cat tst.awk
BEGIN {
    split("BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE",tputColors)
    for (i in tputColors) {
        colorName = tputColors[i]
        colorNr = i-1

        cmd = "tput setaf " colorNr
        fgEscSeq[colorName] = ( (cmd | getline escSeq) > 0 ? escSeq : "<" colorName ">" )
        close(cmd)

        cmd = "tput setab " colorNr
        bgEscSeq[colorName] = ( (cmd | getline escSeq) > 0 ? escSeq : "<" colorName ">" )
        close(cmd)
    }

    cmd = "tput sgr0"
    colorOff = ( (cmd | getline escSeq) > 0 ? escSeq : "<sgr0>" )
    close(cmd)

    FS = ","
}
NR == FNR {
    key = $1
    fgColor[key] = fgEscSeq[$2]
    bgColor[key] = bgEscSeq[$3]
    next
}
{
    # change this to substr($0,41,20) for your real 20-char fields data
    key = substr($0,15,20)  
    gsub(/^[[:space:]]+|[[:space:]]+$/,"",key)
    print bgColor[key] fgColor[key] $0 colorOff
}

Using the pipe to cat -v so you can see color code escape sequences are being output:

$ awk -f tst.awk f1 f2 | cat -v
^[[44m^[[31mfoo      abc            Science   AA^[(B^[[m
^[[47m^[[30mbar      cde  Basic Engineering   AP^[(B^[[m
^[[44m^[[31mbaz     efgh            Science   AB^[(B^[[m

I see you updated your question to say I have already defined color in a seperate file defineColors.sh as: and showed a shell script - just don't use that, it's not needed.

Upvotes: 4

Related Questions