Insert a new line to file after pattern match

Hello,

I’m quite noob in ruby so I’d appreciate a real example:

So, here is:

file1.txt
_Line1
_Line2
_Line3


_LineN

so, read the file and if line match regex insert a nee string right after:

EG: in my case if _Line4 =~/text to search/ => insert new line with a predefined content RIGHT after _Line4.

Ok, i’ve manged to do something but I’ve run into a different problem:

text file

line1

line2
line3
line4
ldap_filters = yes
s
v

demo_add_del.rb
users = %w/user1 user2 user3/
users.length == 1 ? _var = “(#{users[0]})” : _var = ‘(|’ + users.map{|u| “(#{u})”}.join + ‘)’
f = File.open(“ldap_config.conf”).read

f.each_line do |line|
        if  line.match(/ldap_filter_users/)
                f.gsub!(/\sldap_filter_users\s+=.*$/, '#')
                File.write("ldap_config.conf", f)
        elsif line.match(/ldap_filters =/)
                f.gsub!(/ldap_filters = yes/, "ldap_filters = yes\n ldap_filter_users = "+_var)
                File.write("ldap_config.conf", f)

        end
end

NOW:

if I runt 1st time the script get this output =>

line1
line2
line3
line4
ldap_filters = yes
ldap_filter_users = (|(user1)(user2)(user3))
s
v

…and if i runt it 2nd time get this output =>

line1
line2
line3
line4
 ldap_filters = yes
#
#
s
v

Any idea why I’m getting double “#” ?!