是否可以使用2次调用FileEdit在同一个ruby_block中编辑同一行两次? [厨师]

时间:2015-01-28 00:39:20

标签: ruby chef cookbook

嗨,这就是我想要做的事情:

ruby_block "modify line" do
  block do
    file= Chef::Util::FileEdit.new("/someExistingFile.txt")
    file.insert_line_if_no_match(/^11$/, "#this is a comment\n#11")
    file.search_file_replace_line(/^#11$/, "11")
    file.write_file
  end
end

在应用食谱后,它添加了' 11'但是我没有看到#这是一个评论'线。

是否可以连续运行这两行?

file.insert_line_if_no_match(/^11$/, "#this is a comment\n#11")
file.search_file_replace_line(/^#11$/, "11")

预期输出[someExistingFile.txt]:

#this is a comment
11

实际输出[someExistingFile.txt]:

11

另外我改变了这个:

file.insert_line_if_no_match(/^11$/, "#this is a comment\n#11")
file.search_file_replace_line(/^#this is a comment$/, "this is a comment")

预期输出[someExistingFile.txt]:

this is a comment
#11

实际输出[someExistingFile.txt]:

this is a comment

似乎即使很难添加的新行有\nsearch_file_replace_line也认为是1行!为什么呢?

1 个答案:

答案 0 :(得分:1)

FileEdit使用line作为数组,我会尝试深入了解代码中的内容

file.insert_line_if_no_match(/^11$/, "#this is a comment\n#11")

查看代码,这一行会在数组中添加一个条目(里面有一个回车符,但它仍然是一个条目) 方法append_line_if_missing

中的Code here
file.search_file_replace_line(/^#11$/, "11")

如果条目与方法replace_lines

中的Code here匹配,则此方法将替换该条目

这里不明显的是你的开头和结尾锚的正则表达式因\n而匹配,但它是整个数组条目,它被新文本替换而不仅仅是线。

我不确定我的解释是否真的清楚,但希望它有所帮助。