Shell UNIX:grep外卡

 娟紫恋蓝_610 发布于 2023-01-30 07:25

我无法弄清楚为什么在以下示例中使用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

我希望有一个适用于两种情况的实现.我该怎么用?

1 个回答
  • 第一个参数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正则表达式视为要搜索,并在剩余文件中查找它 - 它不会处理来自管道的输入,因为它是给定的文件名参数.

    2023-01-30 07:45 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有