grep filename [星号]返回意外结果 [英] grep filename[asterisk] returns unexpected result
问题描述
我对ls
命令有一个基本问题.
假设在一个目录中,我有4个名为
I have a basic question about ls
command.
Suppose in a directory I have 4 files named
run
run1
running
run.sh
所以,如果我这样做:ls -l|grep run*
,那么我什么都没有.
So, if i do: ls -l|grep run*
then I get no result.
但是,如果我执行ls -l|grep run.*
,那么结果就是run.sh
.
But if i do ls -l|grep run.*
then I get run.sh
as a result.
但是我希望grep
列出这两种情况下的所有文件.
你能让我了解幕后发生的事情吗?
However I expected grep
to list all of the files in both the cases.
Could you make me understand what is going on behind scenes?
推荐答案
据我了解,"*"在执行命令本身之前已由外壳扩展,因此您的grep将尝试使用所有文件名!另一方面,grep期望使用正则表达式,因此不会按预期方式解释"*".
As long as I understand, the "*" is expanded by the shell before executing the command itself, so your grep will try to catch a string with all the file names! On the other hand, grep expects a regular expression, so the "*" is not interpreted as you expect.
直接的解决方案是:
$ ls -l run*
或者,如果您想使用grep,请在"*"后面加上正则表达式:
Or, if you want to use grep, then scape the "*" and provide a regular expression:
$ ls -l|grep run.\*
$ ls -l|grep 'run.*'
这篇关于grep filename [星号]返回意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!