bash - grep'ing 后保留 ls 着色

标签 bash grep colors ls

如果我这样做

$ ls -l --color=always

我得到了目录中的文件列表,其中为不同的文件类型等提供了漂亮的颜色。

现在,我希望能够通过 grep 传输 ls 的彩色输出,以过滤掉一些我不需要的文件。关键是我仍然想保留 grep 过滤器后的颜色。

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

^ grep 后我失去了着色

编辑:我使用的是 headless-server Ubuntu 8.10、Bash 3.2.39,几乎是没有花哨配置的普通安装

最佳答案

您的 grep 可能正在删除 ls 的颜色代码,因为它打开了自己的颜色。

你“可以”这样做:

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

但是,了解您在此处 grepping 的确切内容非常重要。不仅 grepping ls 是不必要的(使用 glob 代替),这种特殊情况是 grepping 不通过仅文件名和文件统计信息,还通过 ls 添加的颜色代码!

您问题的真正答案是:不要 grep 它。永远不需要将 ls 通过管道传输到任何内容或捕获其输出。 ls 仅用于人类解释(例如,仅在交互式 shell 中查看,为此目的它非常方便,类(class))。如前所述,您可以使用 globs 过滤 ls 枚举的文件:

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)

强烈建议您阅读以下两份有关此问题的优秀文档:

关于bash - grep'ing 后保留 ls 着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/867877/

相关文章:

linux - 将查找结果通过管道传输到 grep 中以快速排除目录

bash - 让 grep 在找到匹配项时提前退出

linux - 优化大文件的 grep 操作

javascript - Highchart 中的线条着色需要很长时间

linux - 在 Nodester 安装中丢失

linux - 为什么/root/.bash_profile 中的命令启动了两次?

eclipse - 如何更改默认的 eclipse shell 解释器?

Bash 脚本 := for? 是什么

wpf - 在 WPF 代码隐藏中,如何为每个单独的 ListBoxItem 设置背景颜色,其中颜色基于项目本身?

android - 通过单击按钮更改 Android SDK 中的背景颜色不起作用