0

I have a .txt file in unix directory and i want to color a specific line based on some pattern. please let me know how should i achieve this task.

Also, please let me know, if any documentation can be referred regarding "Coloring of data in a text file"

Maddy
  • 1
  • You miss a point here: txt file does not have any color info in it. You can use a tool to color matches. For instance see - http://stackoverflow.com/questions/981601/colorized-grep-viewing-the-entire-file-with-highlighted-matches – klashar Mar 22 '17 at 15:40
  • Thanks klashar for replying..I would like to rephrase the question.. – Maddy Mar 23 '17 at 08:06
  • The requirement is - "Suppose i have a file in unix and when i "cat" the file, i should see some parts of that file to be highlighted"...The color addition should be a part of the file...I need to know how the color can be give to the contents present in the file. The link you attached, specifies the commands which give us the highlighted data on the run time based on some search pattern. – Maddy Mar 23 '17 at 08:14
  • I am afraid your reqs is not feasible. – klashar Mar 23 '17 at 11:52

1 Answers1

0

Making many assumptions about your environment (eg, this may not work, but it works sometimes), you can make every line that matches the string "foo" red with:

$ RED=$(printf '\033[01;31m')
$ GREEN=$(printf '\033[01;32m')
$ printf 'foo\nbar\n' | sed "/foo/{s/^/$RED/; s/\$/$GREEN/}"

Replace foo in the pattern match with a pattern you want to match, and sed will emit the color codes at the beginning and ending of the line to change the presentation. In this example, I change the color back to green. It is difficult to attempt to restore the color to its previous state, and much simpler to choose a color rather than trying to do so. You can choose a different color code to match your preferred output.

William Pursell
  • 204,365
  • 48
  • 270
  • 300