M Suhayl
M Suhayl

Reputation: 27

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

I tried the above but used a variable and I'm a bit lost.

Upvotes: 0

Views: 246

Answers (2)

dan
dan

Reputation: 5241

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

Assuming you were looking for files matching this regex.

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246942

I bet find uses basic regular expressions by default, so \w is probably not known, and the braces would have to be escaped. Add a -regextype option (and remove -name):

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

Note that my find man page says about -regex:

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

Which means the leading and trailing .* are necessary to ensure the pattern matches the whole path.

And to capture the results into an array (assuming no newlines in the filenames), use the bash mapfile command, redirecting from a process substitution.

mapfile -t files < <(find . -type f -regextype egrep -regex "$re")

Upvotes: 1

Related Questions