bash 在bash中检查文件的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8086378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:03:17  来源:igfitidea点击:

Regular expression to check file in bash

regexfilebash

提问by Kolesar

Is it possible to check whether a file exists with regular expression in bash?

是否可以在bash中使用正则表达式检查文件是否存在?

I tried as follows:

我试过如下:

if [ -f /path/to/file*.txt ]

But unfortunately this does not work.

但不幸的是,这不起作用。

Does anyone know how this is possible?

有谁知道这怎么可能?

回答by thiton

Your approach would work as long as there is exactly one file that matches the pattern. bash expands the wildcard first, resulting in a call like:

只要恰好有一个文件与模式匹配,您的方法就会起作用。bash 首先扩展通配符,导致调用如下:

if [ -f /path/to/file*.txt ]
if [ -f /path/to/file1.txt ]
if [ -f /path/to/file1.txt /path/to/file2.txt ]

depending on the number of matches (0, 1, 2, respectively). To check just for the existence, you might just use find:

取决于匹配的数量(分别为 0、1、2)。要检查是否存在,您可能只需使用 find:

find /path/to -name 'file*.txt' | grep -q '.'

回答by Kuzeko

As @thiton explains the glob(not a real regexp)is expanded and the check fails when multiple files exists matching the glob.

正如@thiton 解释的那样,glob(不是真正的正则表达式)被扩展,并且当存在多个文件与 glob 匹配时检查失败。

You can exploit instead compgenas explained here Test whether a glob has any matches in bashRead more on the man page of compgen

您可以compgen按照此处的说明 进行利用测试 glob 在 bash 中是否有任何匹配项阅读更多信息,请参阅手册页compgen

Here is an example

这是一个例子

if $(compgen -G "/path/to/file*.txt" > /dev/null); then
    echo "Some files exist."
fi