LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1126|回复: 4

请教:为什么*没有匹配上?

[复制链接]
发表于 2008-8-1 13:34:45 | 显示全部楼层 |阅读模式
[root@centos46 ~]# ls -al|grep test
-rw-r--r--   1 root root     41 Jul 31 02:04 test0731
-rw-r--r--   1 root root      0 Jul 31 21:05 test.c
-rw-r--r--   1 root root      0 Aug  1 11:42 test.c.[1-5]
-rw-r--r--   1 root test     79 Jul 30 06:42 testtxt
-rw-r--r--   1 root root     80 Jul 30 04:49 testtxt2
-rw-r--r--   1 root root     80 Jul 30 04:51 testtxt3
-rw-r--r--   1 root test     36 Jul 29 09:10 .vimrc
[root@centos46 ~]#
[root@centos46 ~]#
[root@centos46 ~]# ls -al|grep test.*
[root@centos46 ~]#
[root@centos46 ~]#
[root@centos46 ~]# ls -al|grep test.?
-rw-r--r--   1 root root      0 Jul 31 21:05 test.c
-rw-r--r--   1 root root      0 Aug  1 11:42 test.c.[1-5]

注意用test.*一个也没匹配上。请问为什么呢?
发表于 2008-8-1 14:34:59 | 显示全部楼层
你的用法是错误的,你没明白shell替换与正则表达式的不同。

“ls -al|grep test.*”和“ls -al|grep test.?”在执行匹配之前,shell会自动把“test.*”替换为“test.c test.c.[0-5]”,这样管道就没有意义了,grep也爱莫能助;而“test.?”被替换为“test.c”,此时grep就能匹配出来那两个条目来。你至少应该把grep的$1添上一对单引号。

shell的自动替换功能与grep的正则匹配功能是不一样的,符号“.”、“?”、“*”在两者间的涵义是完全不同的。你要搜索的话,就应该用如下正则式:
  1. ls -al | grep 'test\..*\[*'
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2008-8-2 10:49:00 | 显示全部楼层
谢谢兄弟指点。可惜看了个似懂非懂。更搞怪的事情出来了:
[root@centos46 ~]# ls -al|grep test|awk '{print $NF}'
test0731
test.c
test.c.[1-5]
testtxt
testtxt2
testtxt3
.vimrc


注意,最后连.vimrc都被搜索到了
回复 支持 反对

使用道具 举报

发表于 2008-8-4 07:36:35 | 显示全部楼层
Post by yzhkpli;1881519
谢谢兄弟指点。可惜看了个似懂非懂。更搞怪的事情出来了:
[root@centos46 ~]# ls -al|grep test|awk '{print $NF}'
test0731
test.c
test.c.[1-5]
testtxt
testtxt2
testtxt3
.vimrc


注意,最后连.vimrc都被搜索到了


注意 test group:
-rw-r--r-- 1 root test 36 Jul 29 09:10 .vimrc


What about:

  1. ls -ald test*
复制代码
回复 支持 反对

使用道具 举报

发表于 2008-8-6 00:49:37 | 显示全部楼层
我的感觉就是 grep 里的*匹配前导字符  才导致搂主输出不对
2楼写的
ls -al | grep 'test\..*\[*'

就完全匹配了
表示输出匹配 test.后面跟0个或多个字符之后再跟0个活多个[ 的行
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表