Bash 脚本:将扩展的 glob 模式与字符串数组匹配

问题描述 投票:0回答:1

你好,了不起的人们,

我一直在尝试实现将扩展的全局模式与字符串数组(文件路径)匹配并获取与该模式匹配的文件列表的目标。下面的代码适用于一种 ext glob 模式,但不适用于其他类似的 ext glob 模式。

这是行不通的模式。

pattern="**cars-+(!(bad-cats|dogs))/src/bin/out/**"

这是外壳代码:

#!/bin/bash

# Enable extended globbing
shopt -s extglob


# pattern="**cars-!(bad-cats)/src/bin/out/**" # this extended glob pattern works 
pattern="**cars-+(!(bad-cats|dogs))/src/bin/out/**" # this extended glob pattern doesn't work and also goes in a very long loop cos of cars-ok-kk/src/main/out/start.txt

files="cars-white-pens/src/bin/out/file.txt,cars-ok-kk/src/main/out/start.txt,cars-grey-dogs/src/bin/out/bottle.txt,cars-bad-cats/src/bin/out/computer.txt,cars-whales/src/bin/mouse.txt,cars-dogs/src/bin/out/mouse.txt"
IFS=',' read -r -a files_array <<< "$files"

matching_files=""

for file in "${files_array[@]}"; do
  if [[ $file == $pattern ]]; then
    if [ -z "$matching_files" ]; then
      matching_files="$file"
    else
      matching_files="$matching_files,$file"
    fi
  fi
done

echo "Match: $matching_files"

PS:如果需要代码工作,我们也可以更改 ext glob 模式,但我希望该模式仅是 ext glob 模式,并且支持排除一个或多个目录,如模式中所示。

提前致谢。

注释的 ext glob 模式

pattern="**cars-!(bad-cats)/src/bin/**"
在 shell 脚本中工作得很好,但另一个则不行。

当我运行它时,需要一些时间(不知道为什么),然后打印如下:

Match: cars-white-pens/src/bin/out/file.txt,cars-grey-dogs/src/bin/out/bottle.txt,cars-bad-cats/src/bin/out/computer.txt,cars-dogs/src/bin/out/mouse.txt

它删除了

src/main/out
src/bin/mouse.txt
,但未能删除
cars-bad-cats
cars-dogs
文件字符串。

我期望输出为

Match: cars-white-pens/src/bin/out/file.txt,cars-grey-dogs/src/bin/out/bottle.txt
,因为
src/main/out
src/bin/mouse.txt
不匹配,并且
cars-bad-cats
cars-dogs
被排除。

bash shell sh glob extglob
1个回答
1
投票

不是答案,而是解决方法:

case $file in
*cars-bad-cats/* | *cars-dogs/* ) ;;
*cars*/src/bin/out/* )
    matching_files=${matching_files+$matching_files,}$file
esac
© www.soinside.com 2019 - 2024. All rights reserved.