LoginSignup
3
0

More than 1 year has passed since last update.

テキストファイル読み込み |> 加工 |> テキストファイル書き込み

Last updated at Posted at 2022-01-10

毎回テキストエディタでファイル加工するのが面倒くさいと思ったことはありますよね?
ファイル読み込み
|> 加工
|> ファイル書き込み

の簡単な例を作ってみました。

defmodule YmnTest do
  def convert do
    ret =
      File.read!("in.txt")
      |> String.split("\n")
      |> Enum.filter(fn x -> Regex.match?(~r/"key2":.*/, x) end)
      |> Enum.reduce(fn x, acc -> acc <> "\n" <> x end)
      |> String.replace(~r/[,"]/, "")
      |> String.replace(~r/: /, "\t ")

    File.write("out.txt", ret)
  end
end

加工元のテキスト

in.txt
"key1": "val1",
"key2": "val2",
"key2": "val3",
"key1": "val4",
"key2": "val5",
"key2": "val6"

実行してみよう

$ iex -S mix
Erlang/OTP 24 [erts-12.0] [source] [64-bit] [smp:2:2] [ds:2:2:10] [async-threads:1] [jit]

Compiling 1 file (.ex)
Interactive Elixir (1.12.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> YmnTest.convert
:ok

出力結果

out.txt
key2     val2
key2     val3
key2     val5
key2     val6

1、File.read!で加工元のテキストファイルを読みます
2、String.splitで改行コードで分割し、配列にします
3、Enum.filterで"key2: "を含む行を抽出します
4、Enum.reduceで抽出した配列の結果を改行コードをつけて文字列にします
5、String.replace 「,」と「”」を空に置き換える
6、String.replace 「: 」をタブに置き換える

Enum.filterで欲しい行を抽出し、String.replaceで文字列置き換えをする。
これの組み合わせを作って置けば大量のテキスト処理も楽になると思います。

3
0
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
3
0