grep'ing 后保留 ls 着色 [英] Preserve ls colouring after grep'ing
问题描述
如果我这样做
$ ls -l --color=always
我得到了目录中的文件列表,并为不同的文件类型等做了一些漂亮的着色.
I get a list of files inside the directory with some nice colouring for different file types etc..
现在,我希望能够通过 grep
将 ls
的彩色输出通过管道过滤掉一些我不需要的文件.关键是我还想保留grep过滤后的颜色.
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
^ 我在 grep 之后失去了着色
^ I lose the colouring after grep
我使用的是无头服务器 Ubuntu 8.10、Bash 3.2.39,几乎没有花哨的配置的股票安装
I'm using headless-server Ubuntu 8.10, Bash 3.2.39, pretty much a stock install with no fancy configs
推荐答案
您的 grep 可能正在删除 ls
的颜色代码,因为它打开了自己的颜色.
Your grep is probably removing ls
's color codes because it has its own coloring turned on.
你可以"这样做:
ls -l --color=always | grep --color=never pattern
但是,了解您在此处grep
ping 的确切内容非常重要.不仅 grep
ping ls
是不必要的(使用 glob
代替),这种特殊情况是 grep
ping 不通过仅文件名和文件统计信息,还可以通过 ls
添加的颜色代码!
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
!
您问题的真正答案是:不要grep
.永远不需要将 ls
导入任何东西或捕获其输出.ls
仅用于人类解释(例如,仅在 交互式 shell 中查看,为此它非常方便,课程).如前所述,您可以使用 globs 过滤 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:
- 解析
ls
的坏处说明:http://mywiki.wooledge.org/ParsingLs glob
的力量:http://mywiki.wooledge.org/glob
- Explanation of the badness of parsing
ls
: http://mywiki.wooledge.org/ParsingLs - The power of
glob
s: http://mywiki.wooledge.org/glob
这篇关于grep'ing 后保留 ls 着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!