Why the pipe command "l | grep "1" " get the wrong result?

Lee*_*Lee 13 command-line grep ls pipe

As the picture illustrates, I use l to get the file in the current folder. And then I want to get the file with number 1, so I use the pipe and the grep.

But why the 2 and 22 file show out? And what is the 1;34m?

$ l
./ ../ 1 11 2 22
$ l | grep "1"
1;34m./ 1;32m../ 1 11 2 22
Run Code Online (Sandbox Code Playgroud)

Update

I have already alias the command l in my zshrc file.

 alias lsp="ls"
 alias ll='ls -alF'
 alias la='ls -A'
 alias l='ls -CF'
 alias ls="ls -alh --color"
Run Code Online (Sandbox Code Playgroud)

And here is the result of the type command:

>$ type ls
ls is an alias for ls -alh --color

> $ type l
l is an alias for ls -CF
Run Code Online (Sandbox Code Playgroud)

Ser*_*nyy 26

首先,你试图做的事情l| grep <filename>很糟糕。不要这样做。这是为什么。

l 命令实际上是一个别名 ls -CF

$ type -a l
l is aliased to `ls -CF'
Run Code Online (Sandbox Code Playgroud)

默认情况下,在 Ubuntu 中bash, ,lsls --color=auto. 正如 steeldriver 在评论中指出的那样,--color=auto应该关闭着色。在您的特定情况下,您有alias ls="ls -alh --color"alias l="ls -CF",基本上最终是ls -alh --color -CF。这种特殊的开关组合仍然通过管道发送彩色输出。例如:

$ ls -alh --color -CF ~/TESTDIR | cat -A                                                                                 
^[[0m^[[01;34m.^[[0m/  ^[[01;34m..^[[0m/  1.txt  2.txt  3.txt  out.txt$
Run Code Online (Sandbox Code Playgroud)

注意...目录如何具有相同的转义序列。

这是什么意思呢

这意味着l将根据文件类型输出彩色文件列表。问题是使用转义序列会发生着色。这就是1:34m事情-他们对特定的颜色是转义序列。

主要问题是解析ls经常导致错误的输出和脚本中的灾难,仅仅是因为ls允许像前面解释的转义序列和其他特殊字符。有关更多信息,请参阅本文:http : //mywiki.wooledge.org/ParsingLs

你应该做什么:

使用find命令:

bash-4.3$ ls
1.txt  2.txt  3.txt  out.txt
bash-4.3$ find . -maxdepth 1 -iname "*1*"
./1.txt
Run Code Online (Sandbox Code Playgroud)

你可以用 shell glob 和现代测试[[命令做这样的事情:

bash-4.3$ for file in * ;do if [[ "$file" =~ "1"  ]] ;then echo "$file" ;fi ; done
1.txt
Run Code Online (Sandbox Code Playgroud)

或者也许使用 python,它比bash单独使用具有更好的文件名处理能力

bash-4.3$ python -c 'import os;print [f for f in os.listdir(".") if "1" in f ]'
['1.txt']
Run Code Online (Sandbox Code Playgroud)

如果不需要处理 的输出ls,简单的 globbing withls也可以完成这项工作。(请记住,这仅用于查看文件列表,而不是将其传递给另一个程序来处理输出文本)

bash-4.3$ ls *1*
1.txt
Run Code Online (Sandbox Code Playgroud)

  • 我认为如果还指定了 `--color=always`,输出将仅在管道中着色* - 作为 `l` 的别名的一部分,或者作为 `ls` 本身的前一个别名(替换默认的 `别名 ls='ls --color=auto'`)。 (2认同)

Win*_*nix 6

您的lls命令被设置为别名。

当您运行它们时,通过grep "1"(使用|)管道输出1显示出现的每个屏幕行,1颜色为红色。

因为文件名., ..,222出现在同一屏幕行上,所以它们也会输出,grep但不会以红色显示,这表示grep匹配。

:34m是一个无法正确绘制的颜色的转义序列。根据与输出修改后的问题type -a l,并type -a能在我的系统中再现。请注意,您应该将别名从 更改--color--color=auto

颜色输出

颜色