如何查找与正则表达式匹配的文件并将每个结果保存在数组中?

How to find files matching a regex and save each result in an array?

#!/bin/bash
result=$(find . -type f -name -regex '\w{8}[-]\w{4}[-]\w{4}[-]\w{4}[-]\w{12}')
echo $result

我尝试了上面的方法,但是使用了一个变量,我有点迷路了。

我打赌 find 默认使用基本的正则表达式,所以 \w 可能是未知的,大括号必须被转义。添加 -regextype 选项(并删除 -name):

re='.*[[:alnum:]]{8}-[[:alnum:]]{4}-[[:alnum:]]{4}-[[:alnum:]]{4}-[[:alnum:]]{12}.*'
find . -type f -regextype egrep -regex "$re"

请注意,我的 find 手册页说的是 -regex:

This is a match on the whole path, not a search.

这意味着前导 尾随 .* 是确保模式匹配整个路径所必需的。

并将结果捕获到数组中(假设文件名中没有换行符),使用 bash mapfile 命令,从进程替换重定向。

mapfile -t files < <(find . -type f -regextype egrep -regex "$re")
mapfile -td '' myarray \
< <(find . -type f -regextype egrep \
    -regex '.*/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}' -print0)

# iterate the array in a loop
for i in "${myarray[@]}"; do
    echo "$i"
done

假设您要查找与此正则表达式匹配的文件。