LoginSignup
2
1

More than 5 years have passed since last update.

Chef::Util::FileEditによる処理は、String操作でも簡単に実装可能で、かつ応用もしやすい

Posted at

Chef::Util::FileEditは、以下の様にStringを用いた処理に代替可能で、sedやawkも使いやすい。

Chef::Util::FileEditの例


file '/tmp/text' do
  content lazy {
    f = Chef::Util::FileEdit.new(path)

    f.insert_line_if_no_match(/^ABC\s/, "ABC \n")
    f.search_file_replace_line(/^ABC\s/, "ABC DEF\n")
    f.search_file_delete_line(/^GHI/)

    f.send(:editor).lines.join
  }
end

個人的によく使うのはこの辺り。

Stringによる同等の処理の例

それぞれ以下の様に代替可能


file '/tmp/text' do
  content lazy {
    s = %x(cat #{path})                   # Chef::Util::FileEdit.new相当

    s += "ABC \n" unless s =~ /^ABC\s/    # insert_line_if_no_match 相当
    s = s.gsub(/^ABC\s.*\n/, "ABC DEF\n") # search_file_replace_line 相当
    s = s.gsub(/^GHI.*\n/, '')            # search_file_delete_line 相当

    s                                     # send(:editor).lines.join 相当
  }
end

可読性は落ちるかもしれないが、何をするのかが明確にわかる様になったとも言える。

途中の処理にsedやawkも使える



file '/tmp/text' do
  content lazy {
    s = %x(cat #{path})

    s += "ABC \n" unless s =~ /^ABC\s/
    s = s.gsub(/^ABC\s.*\n/, "ABC DEF\n")

    s = %x( { cat <<'_EOC_'               # sedを使ったsearch_file_delete_line 相当
#{s.chomp}
_EOC_
            } | sed '/^GHI/d'
        )

    s
  }
end

sedやawkが得意な人は好きな方で
echo "#{s}" | sed ... などとしないのは、各種記号が含まれる場合への対応。

参考
- Class: Chef::Util::FileEdit
- Chefによるテキストファイル編集をfileリソースにおけるsed, awkで行う例

2
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
2
1