保护ls着色后grep'ing [英] Preserve ls colouring after grep'ing
问题描述
如果我这样做
$ ls -l --color = always
我得到一个目录中的文件列表,有不同的文件类型等等。
现在,我想能够管道
ls
的彩色输出通过grep
过滤掉一些文件我不需要。关键是我仍然希望在grep过滤器之后保留着色。$ ls -l --color = always | grep -E some_regex
^在grep后失去着色
编辑:我使用无头服务器Ubuntu 8.10,Bash 3.2.39,几乎没有花哨的配置的安装
解决方案您的grep可能会删除
ls
的颜色代码,因为它已打开自己的颜色。
您可以这样做:
ls -l --color = always | grep --color = never pattern
但是,
grep
在这里ping。不仅grep
pingls
不必要(使用glob
),这个特殊情况是grep
不仅通过文件名和文件统计,还通过ls $ c $添加的颜色代码c>!
你的问题的真正答案是:不要
grep
。从来不需要管道ls
任何东西或捕获它的输出。ls
仅供人类解释(例如仅在交互式外壳中查看 它是非常方便,当然)。如前所述,您可以使用globs筛选ls
枚举的文件:ls -l * .txt#显示所有文件名以.txt结尾的文件。
ls -l!(foo).txt#显示所有文件名以.txt结尾但不是foo.txt的文件。 (这需要`shopt -s extglob`开启,你可以把它放在〜/ .bashrc中)
I 高度建议您阅读这两个关于此问题的优秀文档:
- 解析错误的解释
ls
: http://mywiki.wooledge.org/ParsingLs -
glob
s: http://mywiki.wooledge.org/glob
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
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 grep
ping here. Not only is grep
ping ls
unnecessary (use a glob
instead), this particular case is grep
ping 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
glob
s: http://mywiki.wooledge.org/glob
这篇关于保护ls着色后grep'ing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!