我必须遵循功能
#------------------------------------------------------------------------------
# This function just executes one-liner sed command
# to add "line2" after the line that contains "line1"
# in file "file_name"
#------------------------------------------------------------------------------
def add_line2_after_line1_in_file(line1, line2, file_name, comment)
bash comment do
stripped_line2=line2.strip
user 'root'
code <<-EOC
sed -i '/#{line1}/a #{line2}' #{file_name}
EOC
only_if do File.exists? file_name and File.readlines(file_name).grep(/#{stripped_line2}/).size == 0 end
end
end
如何调用函数来生成它?
在调用函数之前
This is a line
Indented line1 \
Indented line2 \
Line3
调用函数后
This is a line
Indented line1 \
Indented line2 \
Added line \
Line3
我试过这个无济于事
add_line2_after_line1_in_file("line1", " line2 \\", "file", "comment")
也许是一个能做同样事情的更好的功能?
答案 0 :(得分:1)
Chef附带了一个Chef::Util::FileEdit
Ruby类(code),可以为您进行此类替换。
ruby_block "Add line to file [c:/path/to/your/file]" do
block do
file = Chef::Util::FileEdit.new("c:/path/to/your/file")
file.insert_line_after_match(/ line2 \\/, " line3 \\" )
file.write_file
end
action :run
end
通过在Ruby中做事,通常更容易与Chef相处。你可以留下诸如shell转义和引用之类的问题,这些问题并不好玩。
如果您有时间,请尝试为您使用的每种方法设置为light weight resource和provider,这样您就可以在任何食谱中轻松重复使用资源,例如:
file_insert_after_line "c:/path/to/your/file" do
search /sometext/
insert_text "new line of text"
end