无法使用grep正则expression式来search包含句点的文件名

Ubuntu 14.x. 使用grep来search所有文件linuxtest-client2 。 这包括多个文件扩展名(csr,crt,key)。 当我grep的中间部分的文件名“2”,它也返回包含“2”除了“2”的行。 当使用ls -l。 这会导致返回文件大小,date和时间中具有“2”的结果。

为什么文件大小在这个grep后面没有句点的时候触发?

root@ip-10-198-0-205:/etc/easy-rsa# ls -ltr keys/ | grep -E '*2.*' total 228 -rw------- 1 root root 3272 Oct 15 18:28 ca.key -rw-r--r-- 1 root root 2451 Oct 15 18:28 ca.crt -rw------- 1 root root 3268 Oct 15 18:31 server.key -rw-r--r-- 1 root root 769 Oct 15 18:42 dh4096.pem -rw-r--r-- 1 root root 8244 Oct 19 15:36 02.pem -rw-r--r-- 1 root root 8250 Oct 19 19:21 03.pem -rw------- 1 root root 3394 Oct 23 19:48 removemetest.key -rw-r--r-- 1 root root 1785 Oct 23 19:48 removemetest.csr -rw-r--r-- 1 root root 8264 Oct 23 19:48 removemetest.crt -rw-r--r-- 1 root root 8264 Oct 23 19:48 04.pem -rw------- 1 root root 3394 Oct 23 20:50 revoketest449.key -rw-r--r-- 1 root root 1789 Oct 23 20:50 revoketest449.csr -rw-r--r-- 1 root root 8270 Oct 23 20:50 revoketest449.crt -rw-r--r-- 1 root root 8270 Oct 23 20:50 05.pem -rw-r--r-- 1 root root 3633 Oct 23 20:50 revoke-test.pem -rw-r--r-- 1 root root 1182 Oct 23 20:50 crl.pem -rw------- 1 root root 3394 Oct 23 20:54 linuxtest-client1.key -rw-r--r-- 1 root root 1793 Oct 23 20:54 linuxtest-client1.csr -rw-r--r-- 1 root root 3 Oct 23 20:54 serial.old -rw-r--r-- 1 root root 8287 Oct 23 20:54 linuxtest-client1.crt -rw-r--r-- 1 root root 909 Oct 23 20:54 index.txt.old -rw-r--r-- 1 root root 21 Oct 23 20:54 index.txt.attr.old -rw-r--r-- 1 root root 8287 Oct 23 20:54 06.pem -rw------- 1 root root 3394 Oct 26 17:57 linuxtest-client2.key -rw-r--r-- 1 root root 1793 Oct 26 17:57 linuxtest-client2.csr -rw-r--r-- 1 root root 3 Oct 26 17:57 serial -rw-r--r-- 1 root root 8287 Oct 26 17:57 linuxtest-client2.crt -rw-r--r-- 1 root root 21 Oct 26 17:57 index.txt.attr -rw-r--r-- 1 root root 1058 Oct 26 17:57 index.txt -rw-r--r-- 1 root root 8287 Oct 26 17:57 07.pem 

但是,如果我不在ls上使用-l,那么它会返回我正在查找的正确结果,所以我的正则expression式是正确的:

 root@ip-10-198-0-205:/etc/easy-rsa# ls keys/ | grep -E '*2.*' 02.pem linuxtest-client2.crt linuxtest-client2.csr linuxtest-client2.key 

Grep默认将该模式视为基本的正则expression式,这意味着. 将匹配任何单个字符。 你可以逃避. 使其意味着一个文字的时期。

 ls -l | grep "2\." 

会给你你正在寻找的,或者你可以告诉grep只search固定的string,而不是正则expression式

 ls -l | grep -F "2." 

既然你给grep -E标志,它实际上会尝试使用扩展正则expression式,但是你似乎正在使用shell通配符,这并不意味着他们在正则expression式中做了什么。 *在正则expression式意味着0或更多的前面的组或字符,和. 意味着任何字符.*在正则expression式意味着0或更多的任何字符。 所以grep -E "*2.*"grep 2是一样的,这就是为什么它在ls -l版本中匹配很多额外的东西

当然,你可以让shell用通配符来处理它

 ls -l *2.*