Reputation: 20410
I need to replace a variable in a Makefile in Ruby
For ex (inside the Makefile):
VAR = 123
What I'm doing is:
puts text.gsub("VAR = 123", "VAR_NEW = 456")
The problem is that I don't know the value, so I would like to use a regular expresion to replace ALL the line containing VAR =
What regular expresion can I use? Can I use a different approach?
Upvotes: 0
Views: 303
Reputation: 7725
You can use a regexp like this:
var = 123
new = 456
text.gsub(/\b#{var}\s?= .+/, "var = #{new}")
Upvotes: 1
Reputation: 349
This tool will help you figure it out http://rubular.com/
Perhaps this
test.gsub(/^(VAR=\s*(['"]?))\d+\2/, $1 + "456" + $2)
That is, if you only want to change value of variable
Edit:
test.gsub(/^(VAR=\s*(['"]?))\d+\2\s*$/, $1 + "456" + $2)
Edit 2
test.gsub(/^(VAR=\s*(['"]?)).*\2\s*$/, $1 + "456" + $2)
Upvotes: 1
Reputation: 868
If i understand correct, you can do this:
irb(main):001:0> text = <<EOF
irb(main):002:0" VAR1 = 111
irb(main):003:0" VAR2 = 222
irb(main):004:0" EOF
=> "VAR1 = 111\nVAR2 = 222\n"
irb(main):005:0> puts text
VAR1 = 111
VAR2 = 222
=> nil
irb(main):007:0> text.gsub!(/^VAR2\s\=\s\d+/, "NEW_VAR = 555")
=> "VAR1 = 111\nNEW_VAR = 555\n"
irb(main):008:0> puts text
VAR1 = 111
NEW_VAR = 555
=> nil
Upvotes: 1