是否可以在bash中使用正则表达式检查文件是否存在?
我尝试如下:
if [ -f /path/to/file*.txt ]
Run Code Online (Sandbox Code Playgroud)
但不幸的是这不起作用。
有谁知道这怎么可能?
只要有一个文件与该模式匹配,您的方法就可以工作。bash 首先扩展通配符,导致如下调用:
if [ -f /path/to/file*.txt ]
if [ -f /path/to/file1.txt ]
if [ -f /path/to/file1.txt /path/to/file2.txt ]
Run Code Online (Sandbox Code Playgroud)
取决于匹配的数量(分别为 0、1、2)。要检查是否存在,您可以使用 find:
find /path/to -name 'file*.txt' | grep -q '.'
Run Code Online (Sandbox Code Playgroud)