我无法弄清楚为什么在以下示例中使用grep对野生字符*进行不同的解释:
find . -type f -name \*
结果:
./tgt/etc/test_file.c ./tgt/etc/speleo/test_file.c ./tgt/etc/other_file.c ./src/file.c
我想从这个命令返回匹配模式的文件,最终是通配符*.但是:
find . -type f -name \* | grep "tgt/etc/*" # this one works find . -type f -name \* | grep tgt/etc/* # not this one find . -type f -name \* | grep tgt/et*/s* # this one works find . -type f -name \* | grep "tgt/et*/s*" # not this one
我希望有一个适用于两种情况的实现.我该怎么用?
第一个参数grep
不是通配符,它是一个正则表达式.在正则表达式中,*
表示匹配其前面的任何数字的字符或表达式.所以
grep "tgt/etc/*"
表示匹配tgt/etc
后跟零个或多个/
字符.在通配符中,*
表示匹配任意数量的任何字符,等效的正则表达式是.*
.出于您的目的,您需要的命令是:
find . -type f -name \* | grep "tgt/etc/" find . -type f -name \* | grep "tgt/et.*/s"
此外,如果您不引用参数,并且它包含任何*
字符,那么shell会将参数扩展为文件名通配符,然后将它们作为参数传递给grep
.所以当你写:
find . -type f -name \* | grep tgt/etc/*
shell将扩展为
find . -type f -name \* | grep tgt/etc/file1 tgt/etc/file2 tgt/etc/file3
这将把tgt/etc/file1
正则表达式视为要搜索,并在剩余文件中查找它 - 它不会处理来自管道的输入,因为它是给定的文件名参数.