嗨,这就是我想要做的事情:
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
似乎即使很难添加的新行有\n
,search_file_replace_line
也认为是1行!为什么呢?
答案 0 :(得分:1)
FileEdit使用line作为数组,我会尝试深入了解代码中的内容
file.insert_line_if_no_match(/^11$/, "#this is a comment\n#11")
查看代码,这一行会在数组中添加一个条目(里面有一个回车符,但它仍然是一个条目)
方法append_line_if_missing
file.search_file_replace_line(/^#11$/, "11")
如果条目与方法replace_lines
这里不明显的是你的开头和结尾锚的正则表达式因\n
而匹配,但它是整个数组条目,它被新文本替换而不仅仅是线。
我不确定我的解释是否真的清楚,但希望它有所帮助。