简体   繁体   English

检查文件是否存在于regex Linux指定的目录中

[英]Check if file exists in a directory specified by regex Linux

I'm trying to use regex inside a file operator to seek for a file where one subdirectory is specified with a regex, but I wonder if it's even possible. 我正在尝试在文件运算符中使用regex来查找其中一个用regex指定一个子目录的文件,但是我想知道是否有可能。 I think I tried all the quote and bracket combinations possible. 我想我尝试了所有可能的引号和括号组合。 Either I'm missing something here, or a file operator requires a specific path? 我在这里缺少什么,还是文件操作符需要特定的路径?

I'm not entirely sure. 我不太确定。 Could somebody please clarify? 有人可以澄清一下吗?

What I want to achieve is something like this (this obviously doesn't work because it takes the regex part as name of the subdirectory) 我想要实现的是这样的事情(这显然不起作用,因为它将正则表达式部分作为子目录的名称)

if [[ -r '/agent/[0-9 .]*/bin/run.sh' ]]

find has a -regex option 查找具有-regex选项

-regex pattern -regex模式

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.' 例如,要匹配名为./fubar3', you can use the regular expression的文件./fubar3', you can use the regular expression 。* bar。 or .*b.*3 , but not f.*r3 . .*b.*3 ,而不是f.*r3 The regular expressions understood by find are by default Emacs Regular Expressions, but this can be changed with the -regextype option. find可以理解的正则表达式默认是Emacs正则表达式,但是可以使用-regextype选项进行更改。

if find . -regex '/agent/[0-9 \.]*/bin/run.sh'

According to the manual , only the =~ operator does regex matching. 根据手册 ,仅=〜运算符进行正则表达式匹配。

There's another way though: 但是还有另一种方法:

RUNFILES=$( find /agent -name run.sh | grep -e '^/agent/[0-9 .]*/bin/run.sh$' )
if [ -n "$RUNFILES" ]
then
[...]
fi

您可以简单地使用ls命令和正则表达式:

if ls /agent/[0-9\ .]*/bin/run.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM