用 GNU find 理解 -regex

Thi*_*his 3 find xargs regular-expression

背景

我有我认为应该是一个简单的案例。我想找到名称中带有“cisco”的所有文件,并对这些文件进行处理(通过xargs)。

查找文件 ls

在我使用xargs之前,第一步是列出所有相关文件。列出文件很容易ls | grep cisco...

[mpenning@Bucksnort post]$ ls | grep cisco
cisco-asa-double-nat.rst
cisco-asa-packet-capture.rst
cisco-eem-tcl.rst
cisco-ip-sla-tracking.rst
cisco_autonomous_to_lwap.rst
[mpenning@Bucksnort post]$
Run Code Online (Sandbox Code Playgroud)

查找文件 find

尽管在这种特定情况下可能不需要它,但是当管道进入xargs时,通常认为find更安全。但是,当我使用.find -regex

[mpenning@Bucksnort post]$ find -regextype grep -regex ".*/cisco*" -print
[mpenning@Bucksnort post]$
Run Code Online (Sandbox Code Playgroud)

但是,我知道我可以找到这些文件...

[mpenning@Bucksnort post]$ find | grep cisco
./cisco-eem-tcl.rst
./parsing-cisco-output-w-textfsm.rst
./cisco_autonomous_to_lwap.rst
./cisco-ip-sla-tracking.rst
./cisco-asa-double-nat.rst
./cisco-asa-packet-capture.rst
[mpenning@Bucksnort post]$
Run Code Online (Sandbox Code Playgroud)

问题

我意识到find -regex必须匹配返回的完整路径,但为什么不能find -regextype grep -regex ".*/cisco*" -print在上面工作?不应该.*/cisco*匹配路径吗?


笔记

我知道我可以find -path "*cisco*"用来解决问题,但问题的关键是要了解为什么我的-regex用法是错误的。

Ale*_*ios 6

查找 withls : first things first,ls | grep cisco有点冗长,因为cisco它不是正则表达式。尝试:

ls *cisco*
Run Code Online (Sandbox Code Playgroud)

使用find: 沿着相同的路线,-regex使用简单的静态模式是矫枉过正的。怎么样:

find -name '*cisco*'
Run Code Online (Sandbox Code Playgroud)

引号是必需的,因此 glob 由 解释find,而不是 shell。此外,-print的许多版本都需要find,但对于其他版本(例如 GNU find)是可选的(和默认谓词)。如果需要,请随意添加。

如果您需要在完整路径名中搜索“cisco”,您可以尝试以下操作:

find -path '*cisco*'
Run Code Online (Sandbox Code Playgroud)

这相当于find | fgrep cisco.

find与正则表达式一起使用:无论如何,让我们这样做,因为这就是您想要的。无耻地从 GNUfind联机帮助页复制:

-正则表达式模式

          File  name  matches  regular  expression  pattern.  This is a match
          on the whole path, not a search.  For example, to match a file named
          `./fubar3', you can use the regular expression `.*bar.' or `.*b.*3',
          but not `f.*r3'.
Run Code Online (Sandbox Code Playgroud)

这意味着您的正则表达式包含在一个 invisible 中^...$,因此它必须匹配文件完整路径名中的每个字符。因此,正如 nwildner 和 otokan 在评论中所说,您应该使用以下内容:

find -regex '.*cisco.*'
Run Code Online (Sandbox Code Playgroud)

而且你甚至不需要-regextype这个简单的东西。