Saving output of a grep into a file with colors
To keep the markup, you need more than just a text file. I'd use HTML output to keep the colors.
-
Install aha i.e. to "converts ANSI escape sequences of a unix terminal to HTML code"
sudo apt-get install aha
-
then save your
grep
(orls
) output like this:ls --color=always | aha --black --title 'ls-with-colors' > ls-with-colors.html
options:
--black param to set background as black color --title param to set the title for HTML page
Syntax highlight for file extension via pygmentize
-
install
pygmentize
:sudo apt-get install python-pygments
-
then run this kind of command:
pygmentize file.pl | grep -i --color=always version | aha --black > ls-with-colors.html
Depending on what you're wanting to do with the output file, it's possible to add colors to a 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.