gpt4 book ai didi

bash - shell UNIX : grep wild card

转载 作者:行者123 更新时间:2023-11-29 09:18:20 24 4
gpt4 key购买 nike

我不明白为什么在以下使用 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 视为要搜索的正则表达式,并在其余文件中查找它——它不会处理输入来自管道,因为它被赋予了文件名参数。

关于bash - shell UNIX : grep wild card,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21492833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com