这里的红宝石新手!
如何使用ruby替换包含特定字符串的文本文件中的整行?
示例:我想删除并添加包含“ DB_URL ”的整行,并添加“ DB_CON = jdbc:mysql:replication:// master,slave1,slave2,slave3”之类的内容/测试“
DB_URL=jdbc:oracle:thin:@localhost:TEST
DB_USERNAME=USER
DB_PASSWORD=PASSWORD
答案 0 :(得分:1)
这是您的解决方案。
file_data = ""
word = 'Word you want to match in line'
replacement = 'line you want to set in replacement'
IO.foreach('pat/to/file.txt') do |line|
file_data += line.gsub(/^.*#{Regexp.quote(word)}.*$/, replacement)
end
puts file_data
File.open('pat/to/samefile.txt', 'w') do |line|
line.write file_data
end
答案 1 :(得分:0)
这是我的尝试:
<强> file.txt的强>
First line
Second line
foo
bar
baz foo
Last line
<强> test.rb 强>
f = File.open("file.txt", "r")
a = f.map do |l|
(l.include? 'foo') ? "replacing string\n" : l # Please note the double quotes
end
p a.join('')
<强>输出强>
$ ruby test.rb
"First line\nSecond line\nreplacing string\nbar\nreplacing string\nLast line"
我发表了# Please note the double quotes
评论,因为单引号将转义\n
(将成为\\n
)。此外,您可能想要考虑文件的最后一行,因为它会在最后一行的末尾添加\n
,而原始文件的末尾没有。{1}}。如果你不希望你能做出类似的事情:
f = File.open("file.txt", "r")
a = f.map do |l|
(l.include? 'foo') ? "replacing string\n" : l
end
a[-1] = a[-1][0..-2] if a[-1] == "replacing string\n"
p a.join('')