Color escape codes in pretty printed columns

前端 未结 4 734
攒了一身酷
攒了一身酷 2020-12-18 00:39

I have a tab-delimited text file which I send to column to \"pretty print\" a table.

Original file:

1blablablabla

        
4条回答
  •  萌比男神i
    2020-12-18 01:12

    In my case, I wanted to selectively colorise values in a column depending on its value. Let's say I want okokokok to be green and blabla to be red.

    I can do it such way (the idea is to colorise values of columns after columnisation):

    GREEN_SED='\\033[0;32m'
    RED_SED='\\033[0;31m'
    NC_SED='\\033[0m' # No Color
    
    column -s$'\t' -t  | echo -e "$(sed -e "s/okokokok/${GREEN_SED}okokokok${NC_SED}/g" -e "s/blabla/${RED_SED}blabla${NC_SED}/g")"
    

    Alternatively, with a variable:

    DATA=$(column -s$'\t' -t )
    
    GREEN_SED='\\033[0;32m'
    RED_SED='\\033[0;31m'
    NC_SED='\\033[0m' # No Color
    echo -e "$(sed -e "s/okokokok/${GREEN_SED}okokokok${NC_SED}/g" -e "s/blabla/${RED_SED}blabla${NC_SED}/g" <<< "$DATA")"
    

    Take a note of that additional backslash in values of color definitions. It is made for sed to not interpret an origingal backsash.

    This is a result:

提交回复
热议问题