码迷,mamicode.com
首页 > 其他好文 > 详细

Saving output of a grep into a file with colors

时间:2015-05-02 01:04:54      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

I need to save the result of a grep command into a file, but I also want the output file to be formatted and keep the colors just like in the terminal.

Is there a way to do that? Maybe make grep save to a some kind of markup language? If it is not possible, is there another tool that can accomplish this task?

I am trying to make the search keyword stand out in the output file, exactly like it does in the terminal.

Depending on what you‘re wanting to do with the output file, it‘s possible to add colors to normal text file, because the colors simply come from some special characters. Grep seems to not want to print them when you redirect it to a file, so you need to force it to:

grep --color=always "stuff" input.txt > output.txt

Now, when you print the file to the console it will be printed with the colors, because Bash interprets those characters as "use this color".

cat output.txt

However, if you open it in an editor like vim, you‘ll get some strange characters. For example, when I use the commands

echo "A sentence. A red sentence. Another sentence."   | grep --color=always "A red sentence" > output.txt

The output looks right when I print it using cat but when I open it in vim I get

A sentence. ^[[01;31m^[[KA red sentence^[[m^[[K. Another sentence.

So if you‘re wanting to use an editor this probably isn‘t what you want.

Saving output of a grep into a file with colors

标签:

原文地址:http://www.cnblogs.com/zhaoxinshanwei/p/4471466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!