ls | grep 不适用于 ls --color

dan*_*996 2 ls grep colors regular-expression

我正在尝试使用以下命令列出所有隐藏的目录

ls -lhAF1 | grep -E '^d.*[0-9]{2}:[0-9]{2} \.'
Run Code Online (Sandbox Code Playgroud)

这工作得很好

正则表达式的解释:我试图获取所有具有以下格式的行:d,然后是一些文本,然后是时间戳,然后是一个空格,然后是点,然后是更多文本

但是,当我尝试使用此命令为 ls 输出着色时:

ls --color -lhAF1 | grep -E '^d.*[0-9]{2}:[0-9]{2} \.'
Run Code Online (Sandbox Code Playgroud)

它给出零结果,没有的输出--color是:

drwxr-xr-x 1 用户组 4096 Feb 1 08:48 .invisible

为什么 ls / grep 会这样?

小智 6

--color为颜色添加转义序列。如果将输出(of ls --color)重定向到文件,则可以看到这一点。

这是它的样子:

 drwxr-xr-x  6 root root 4.0K Jan  9 08:23 ^[[01;34m.cabal^[[0m/
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,试试这个:

 ls -lhAF1 --color | grep -E '^d.*[0-9]{2}:[0-9]{2} .*\.'
Run Code Online (Sandbox Code Playgroud)


roa*_*ima 6

解析ls往往是一个坏主意。经常,但不总是。这是给您的另一个建议,它在将集合传递给ls.

find .* -maxdepth 0 -type d \( -name '.[^.]' -o -name '.??*' \) -exec ls -ld --color=always {} +
Run Code Online (Sandbox Code Playgroud)

有人指出,原始代码实际上将目录列表限制为在过去六个月中修改过的目录。这可以通过以下替代解决方案来处理。

find .* -maxdepth 0 -type d -mtime -180 -mtime +0 \( -name '.[^.]' -o -name '.??*' \) -exec ls -ld --color=always {} +
Run Code Online (Sandbox Code Playgroud)

与以往一样,如果您find不了解尾随+,请以\;效率为代价将其替换。