替换文件中匹配的行,但使用Ruby忽略注释掉的行
如何在Ruby中替换文件,但不涉及注释行?更具体地说,我想更改配置文件中的变量。例如:替换文件中匹配的行,但使用Ruby忽略注释掉的行,ruby,regex,Ruby,Regex,如何在Ruby中替换文件,但不涉及注释行?更具体地说,我想更改配置文件中的变量。例如: irb(main):014:0> string = "#replaceme\n\t\s\t\s# replaceme\nreplaceme\n" => "#replaceme\n\t \t # replaceme\nreplaceme\n" irb(main):015:0> puts string.gsub(%r{replaceme}, 'replaced') #replaced
irb(main):014:0> string = "#replaceme\n\t\s\t\s# replaceme\nreplaceme\n"
=> "#replaceme\n\t \t # replaceme\nreplaceme\n"
irb(main):015:0> puts string.gsub(%r{replaceme}, 'replaced')
#replaced
# replaced
replaced
=> nil
irb(main):016:0>
期望输出:
#replaceme
# replaceme
replaced
这个怎么样
puts string.gsub(%r{^replaceme}, 'replaced')
我不完全理解这个问题。要在每行中查找并替换,不考虑磅符号后面的文本,可以执行以下操作
def replace_em(str, source, replacement)
str.split(/(\#.*?$)/).
map { |s| s[0] == '#' ? s : s.gsub(source, replacement) }.
join
end
str = "It was known that # that dog has fleas, \nbut who'd know that that dog # wouldn't?"
replace_em(str, "that", "the")
#=> "It was known the # that dog has fleas, \nbut who'd know the the dog # wouldn't?"
str = "#replaceme\n\t\s\t\s# replaceme\nreplaceme\n"
replace_em(str, "replaceme", "replaced")
#=> "#replaceme\n\t \t # replaceme\nreplaced\n"
对于字符串
str = "It was known that # that dog has fleas, \nbut who'd know that that dog # wouldn't?"
source = "that"
replacement = "the"
步骤如下
a = str.split(/(\#.*?$)/)
#=> ["It was known that ", "# that dog has fleas, ",
# "\nbut who'd know that that dog ", "# wouldn't?"]
请注意,正则表达式的主体必须放在捕获组中,以便用于拆分字符串的文本作为元素包含在结果数组中。看
谢谢你。事实上,我需要非常高质量的替代品,在100%的情况下工作。因此,即使是第
行“此处某物替换我#注释”
也应该替换为“此处某物替换#注释”
,作为一个例子,如果string=“cat cat#cat\ncat cat”
和“cat”
被替换为“dog”
,那么期望的结果是“dog dog dog dog”`?我主要感兴趣的是知道每行是否可以有多个替换。根据您的示例:dog dog\cat\ncat cat
和dog
。那么,是否有可能进行正常的替换,但当发现时,忽略该行,但仅从何处开始?这与Linux命令行的工作原理完全相同。它只执行命令,直到到达#。如果这有帮助的话,多个GSUB是可以的。我不明白为什么“cat cat”
后面的“\n”
不会更改为“dog dog”
,因为那一行中没有英镑符号。对不起,我错过了最后一行应该是“dog dog”
。我已把你的答案标为正确答案。做得好!效果很好。所以这个机制可以修改配置文件,但是注释掉的行不会被触及,因为不需要。这可以用于厨师,木偶和其他。例如,Chef在默认情况下不提供此功能,并且内置的FileEdit存在一些多字节问题,因此此解决方案是Ruby中的通用解决方案。
b = a.map { |s| s[0] == '#' ? s : s.gsub(source, replacement) }
#=> ["It was known the ", "# that dog has fleas, ",
# "\nbut who'd know the the dog ", "# wouldn't?"]
b.join
#=> "It was known the # that dog has fleas, \nbut who'd know the the dog # wouldn't?"