2

I am trying to change the colors of content of a file conditionally. My file is:

A  B  C  D
Value  Value  Value  Value  
Value  Value  Value  Value  
Value  Value  Value  Value  
Value  Value  Value  Value  

My command is cat file4 | sed "s,.*,${esc}[33m&${esc}[0m,", whose logic I understand to be:

  1. Cat the file then by sed command edit the contents color by using the ANSI color codes.

But when I run this file generated is not as per desired:

[33mA  B  C  D[0m
[33mValue  Value  Value  Value  [0m
[33mValue  Value  Value  Value  [0m
[33mValue  Value  Value  Value  [0m
[33mValue  Value  Value  Value  [0m

Desired Output:

  • Field A should be red.
  • Field C should be in blue.
  • Field D should be yellow.
  • Field B should be green.
2

Firstly, this is a UUOC (useless use of cat). There is no good eason to use cat here, sed is perfectly able to read files itself, and even if it wasn't, then redirecting standard input from the file would be equivalent to piping it.

esc=$(echo -e '\e')
sed "s,\(.*\)  \(.*\)  \(.*\)  \(.*\),$esc[31m\1  $esc[34m\2  $esc[33m\3  $esc[32m\4$esc[m," file4

This is assuming the two spaces between the fields as you originally specified although that seems to have gone in an edit; adjust accordingly.

I have no idea why you thought your original way (match all text on a line, wrap it between two escape codes (for yellow) would give you multiple colours.

  • please tell me how you managed the <space> logic here – Aman Apr 17 '15 at 12:02
  • it has bug that it is providing colors to 3 values in a fields only I wanted that for column A all values in a one color , for column B all columns in a one color and so on – Aman Apr 17 '15 at 12:05
  • It's always easier for such things to be e.g. tab separated. If you're sure the column values won't contain spaces then replace the .* with [^ ]*. Besides that the script works fine as long as the input has exactly 4 columns separated by precisely 2 spaces, with no trailing spaces. – wurtel Apr 17 '15 at 12:24
  • Its working now :) – Aman Apr 20 '15 at 5:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.