如何用Ruby正则仅修改以Mary开头行中的banana为orange?
Ruby正则实现仅修改特定开头行中的指定词汇(Chef Cookbook场景)
针对你的需求,要仅修改以Mary开头的行里的banana为orange,可以利用Ruby正则的多行模式和匹配重置特性实现,以下是具体方案:
核心正则说明
使用正则/(?m)^Mary.*\Kbanana/,各部分作用:
(?m):启用多行模式,让^匹配每一行的开头^Mary:精准定位以Mary开头的目标行.*:匹配该行中Mary到banana之间的所有内容\K:丢弃之前匹配的内容,仅将后续的banana作为替换目标banana:指定需要替换的词汇
Ruby代码示例
直接执行替换的测试代码:
original_content = <<~TEXT Mike likes banana, kiwi and grapes. Mary likes banana, apple and watermelon. TEXT modified_content = original_content.gsub(/(?m)^Mary.*\Kbanana/, 'orange') puts modified_content
执行后输出符合预期:
Mike likes banana, kiwi and grapes.
Mary likes orange, apple and watermelon.
Chef Cookbook中的实际应用
方式1:通过file资源修改文件
file '/path/to/your/fruits.txt' do action :create content lazy { current_content = File.read('/path/to/your/fruits.txt') current_content.gsub(/(?m)^Mary.*\Kbanana/, 'orange') } end
方式2:通过ruby_block执行替换
ruby_block 'update_marys_fruit_preference' do block do file_path = '/path/to/your/fruits.txt' content = File.read(file_path) modified_content = content.gsub(/(?m)^Mary.*\Kbanana/, 'orange') File.write(file_path, modified_content) end only_if { File.exist?('/path/to/your/fruits.txt') } end
内容的提问来源于stack exchange,提问作者Hasan
相关产品推荐
相关产品推荐

