Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve ls colouring after grep'ing

Tags:

grep

bash

colors

ls

If I do

$ ls -l --color=always 

I get a list of files inside the directory with some nice colouring for different file types etc..

Now, I want to be able to pipe the coloured output of ls through grep to filter out some files I don't need. The key is that I still want to preserve the colouring after the grep filter.

$ ls -l --color=always | grep -E some_regex 

^ I lose the colouring after grep

EDIT: I'm using headless-server Ubuntu 8.10, Bash 3.2.39, pretty much a stock install with no fancy configs

like image 574
duckyflip Avatar asked May 15 '09 10:05

duckyflip


1 Answers

Your grep is probably removing ls's color codes because it has its own coloring turned on.

You "could" do this:

ls -l --color=always | grep --color=never pattern 

However, it is very important that you understand what exactly you're grepping here. Not only is grepping ls unnecessary (use a glob instead), this particular case is grepping through not only filenames and file stats, but also through the color codes added by ls!

The real answer to your question is: Don't grep it. There is never a need to pipe ls into anything or capture its output. ls is only intended for human interpretation (eg. to look at in an interactive shell only, and for this purpose it is extremely handy, of course). As mentioned before, you can filter what files ls enumerates by using globs:

ls -l *.txt      # Show all files with filenames ending with `.txt'. ls -l !(foo).txt # Show all files with filenames that end on `.txt' but aren't `foo.txt'. (This requires `shopt -s extglob` to be on, you can put it in ~/.bashrc) 

I highly recommend you read these two excellent documents on the matter:

  • Explanation of the badness of parsing ls: http://mywiki.wooledge.org/ParsingLs
  • The power of globs: http://mywiki.wooledge.org/glob
like image 179
lhunath Avatar answered Oct 04 '22 03:10

lhunath