加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell – 文件glob()何时**理解?

发布时间:2020-12-15 22:00:46 所属栏目:安全 来源:网络整理
导读:在 Java7中,sun.nio.fs.Globs和getPathMatcher()似乎理解成语**作为跨目录边界匹配零个或多个字符的方法(参见 the getPathMatcher javadoc). 我可以发誓一些shell(zsh,bash,tcsh)的一些适当的选项设置让我在某些时候有相同的行为.但对于我的生活,我不记得如
在 Java7中,sun.nio.fs.Globs和getPathMatcher()似乎理解成语**作为跨目录边界匹配零个或多个字符的方法(参见 the getPathMatcher javadoc).

我可以发誓一些shell(zsh,bash,tcsh)的一些适当的选项设置让我在某些时候有相同的行为.但对于我的生活,我不记得如何实现这一点,我甚至开始怀疑我的记忆,我在某些时候让它工作……(编辑:zsh提供了这种行为,但只针对目录,即“ **.gz“与foo / bar / fubar.gz不匹配,但是”** / * .gz“确实如此).

事实上,查看各种glob实现的文档(例如POSIX glob(3),glob(7)和Perl的File :: Glob),这种行为似乎没有在任何地方提到过.一个例外是Ruby的Dir.glob(),它明确地处理**.

(原始问题是:“有没有人知道如何在unix shell中启用此行为(例如zsh)?”,但现在看到下面的编辑问题).

作为一个额外的问题:有没有人知道如何在Google中搜索“**”?…

编辑问题

实际上,看起来我的zsh shell确实接受了这种行为(感谢响应断言这一事实??并促使我进一步观察).我认为它不是来自以下微妙的原因:“**.gz”与< path> /<前缀> .gz不匹配,但“** / * .gz”将匹配.这是一个例子.让我们从以下树开始:

$find . -type f | sort
./foo/a.gz
./foo/bar/fubar/abc.gz
./foo/bar/x.gz
./foo/bar/y.gz
./xyz.gz

“**.gz”与内部子目录不匹配,只匹配“* .gz”:

$ls -1 **.gz
xyz.gz

而“** / * .gz”确实:

$ls -1 **/*.gz
foo/a.gz
foo/bar/fubar/abc.gz
foo/bar/x.gz
foo/bar/y.gz
xyz.gz

现在,将其与Java行为进行比较:

@Test
public void testStar() {
    String pat = Globs.toUnixRegexPattern("*.gz");
    assertEquals("^[^/]*.gz$",pat);
}

@Test
public void testStarStar() {
    // '**' allows any number of directories on the path
    // this apparently is not POSIX,although darn useful
    String pat = Globs.toUnixRegexPattern("**.gz");
    assertEquals("^.*.gz$",pat);
}

显然(来自正则表达式),这里“**”匹配路径上的任何字符(即它在regexp中变为“.*”),无论是否在子目录中,以及作为文件名的一部分.

(免责声明:Globs是sun.nio.fs.Globs.toUnixRegexPattern(String glob)的副本,因为我需要一些跨平台工作的东西).

解决方法

在 POSIX shell:

The slash character in a pathname shall be explicitly matched by using
one or more slashes in the pattern; it shall neither be matched by the
asterisk or question-mark special characters nor by a bracket
expression

你可以谷歌:“文件名扩展模式”.

在bash中你可以设置globstar

[An asterisk] Matches any string,including the null string. When the globstar shell
option is enabled,and ‘*’ is used in a filename expansion context,
two adjacent ‘*’s used as a single pattern will match all files and
zero or more directories and subdirectories. If followed by a ‘/’,two
adjacent ‘*’s will match only directories and subdirectories.

$shopt -s globstar
$ls **/
$shopt -u globstar
$ls **/

注意:此处使用’/’仅显示目录.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读