5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Elixirでディレクトリ内のファイルを一覧を取得する。

Last updated at Posted at 2023-08-13

Elixirでディレクトリ内のファイルを列挙する方法について調べました。

これからElixirを始める方にはこのサイトがおすすめです。

Elixirとコミュニティの雰囲気をゆるく味わいたい方は「先端ピアちゃん」さんの動画が超オススメです。

結論

File.ls!/1Path.wildcard/1がお手軽で便利でした。

他にも技がありましたら、ぜひお便りください!

実験の準備

ターミナルを開き実験用のディレクトリとファイルを作成します。

# 実験用のディレクトリを準備。
mkdir -p tmp/hoge

# 実験用のディレクトリに入る。
cd tmp/hoge

# いろんなタイプのファイルを作成。
touch {元氣,闘魂}-{1..3}.{exs,json}

# ちゃんとファイルが生成されたか確認。
ls

IExで実験

# IExを開く。
iex

# File.ls!/1 で現行ディレクトリにある全てのファイルを列挙する。
iex> File.ls!(".")
["闘魂-3.json", "闘魂-2.json", "元氣-3.json", "闘魂-1.exs",
 "闘魂-3.exs", "元氣-2.json", "闘魂-2.exs", "元氣-3.exs",
 "元氣-1.json", "元氣-2.exs", "元氣-1.exs", "闘魂-1.json"]

# 引数無しの場合でも同様に現行ディレクトリで検索がなされる。
iex> File.ls!()
["闘魂-3.json", "闘魂-2.json", "元氣-3.json", "闘魂-1.exs",
 "闘魂-3.exs", "元氣-2.json", "闘魂-2.exs", "元氣-3.exs",
 "元氣-1.json", "元氣-2.exs", "元氣-1.exs", "闘魂-1.json"]

# Path.wildcard/1 でexsファイルだけ列挙する。
iex> Path.wildcard("./*.exs")
["元氣-1.exs", "元氣-2.exs", "元氣-3.exs", "闘魂-1.exs", "闘魂-2.exs",
 "闘魂-3.exs"]

# Path.wildcard/1 で元氣ファイルだけ列挙する。
iex> Path.wildcard("./元氣-*")
["元氣-1.exs", "元氣-1.json", "元氣-2.exs", "元氣-2.json",
 "元氣-3.exs", "元氣-3.json"]

# jsonファイルを削除。
iex> Path.wildcard("./*.json") |> Enum.each(&File.rm!/1)
:ok

iex> File.ls!()
["闘魂-1.exs", "闘魂-3.exs", "闘魂-2.exs", "元氣-3.exs", "元氣-2.exs",
 "元氣-1.exs"]

# exsファイルを削除。
iex> Path.wildcard("./*.exs") |> Enum.each(&File.rm!/1)
:ok

iex> File.ls!()
[]

:tada:

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?