0

Hi this is what I'm trying to do:

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

After applying the cookbook it adds '11' but I don't see the '#this is a comment' line.

is it possible to run this two lines consecutively?

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

Expected output [someExistingFile.txt]:

#this is a comment
11

Actual output [someExistingFile.txt]:

11

In addition I changed it around like this:

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")

Expected output [someExistingFile.txt]:

this is a comment
#11

Actual output [someExistingFile.txt]:

this is a comment

It seems that even tough the new line added had a \n the search_file_replace_line thinks as both as 1 line!! why?

david
  • 741
  • 3
  • 10
  • 29
  • sorry, maybe it's just late and I'm not thinking clear. Can you give us a short sample of the starting file, the expected end state, and the endstate you are actually getting? Thanks. – Tejay Cardon Jan 28 '15 at 02:22
  • I added the endstate and what I'm actually getting. – david Jan 28 '15 at 02:29

1 Answers1

1

FileEdit works with line as an array, I'll try to give insight on what is done in your code

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

Looking at the code this line will add one entry to the array (with a carriage return inside, but it's still one entry) Code here in method append_line_if_missing

file.search_file_replace_line(/^#11$/, "11")

This method will replace the entry if it match Code here in method replace_lines

What's not obvious here is that your regex with start and end anchors match because of the \n but it's the whole array entry which is replaced by the new text and not only the line.

Not sure I'm really clear on my explanation, but hope it give some light.

Tensibai
  • 15,557
  • 1
  • 37
  • 57
  • yes it makes complete sense! do you know if there is a way I can accomplish the desired results? – david Jan 28 '15 at 15:24
  • I would use two ruby_block ... or maybe call the `file.write_file`, and reopen the file between the two operations. Poke @coderanger as he may have a better way (he's better than me when playing with inner chef code and advanced ruby) – Tensibai Jan 28 '15 at 15:28