24

In Ruby, I can use

target_files = Dir["/some/dir/path/*.rb"]
#=> ["/some/dir/path/foo.rb", "/some/dir/path/bar.rb", "/some/dir/path/baz.rb"]

which will return an array of all of the matching files in a directory. How can I do something similar in Elixir?

1

3 Answers 3

38

You're looking for Path.wildcard/2:

iex(1)> Path.wildcard("/tmp/some/dir/path/*.rb")
["/tmp/some/dir/path/bar.rb", "/tmp/some/dir/path/baz.rb",
 "/tmp/some/dir/path/foo.rb"]
iex(2)> Path.wildcard("/tmp/**/*b*.rb")
["/tmp/some/dir/path/bar.rb", "/tmp/some/dir/path/baz.rb"]
Sign up to request clarification or add additional context in comments.

2 Comments

Path.wildcard("/tmp/some/dir/path/*.rb") |> Enum.map(&Path.basename/1) will output ["bar.rb", "baz.rb", "foo.rb"] in case you only need file name.
@Dogbert - the link above is broken. It's here now - hexdocs.pm/elixir/Path.html#wildcard/2
6

And if you want to recursively gather files with a regex, there's :filelib.fold_files/5.

Comments

1

Path.wildcard/1 can handle recursive folders with two stars '**' (it works similar to Dir.glob in Ruby). E.g.

Path.wildcard("../data/??/**/*.yml")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.