【问题标题】:Replace whole line with sub-string in a text file - Ruby用文本文件中的子字符串替换整行 - Ruby
【发布时间】:2016-10-02 02:56:13
【问题描述】:

这里是 ruby​​ 新手!

如何使用 ruby​​ 替换包含特定字符串的文本文件中的整行?

示例:我想删除并添加包含“DB_URL”的整行并添加类似“DB_CON=jdbc:mysql:replication://master,slave1,slave2,slave3 /test"

DB_URL=jdbc:oracle:thin:@localhost:TEST DB_USERNAME=USER DB_PASSWORD=PASSWORD

【问题讨论】:

  • 只是为了确定,你想替换一行还是句子? (每行可以有几个句子)
  • 举个例子并描述你到目前为止所做的尝试。
  • 我对代码进行了更改,请检查一下,如果旧的更好,请告诉我。

标签: ruby file text io


【解决方案1】:

这是我的尝试:

文件.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,而原始文件的末尾不会有一个。如果你不想这样,你可以做类似的东西:

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('')

【讨论】:

  • 与其把代码扔在墙上,不如解释一下代码的作用以及它如何帮助解决问题。这通常比实际代码更有价值,因为它可以帮助人们理解和解决未来的类似问题。
【解决方案2】:

这是您的解决方案。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 2012-11-06
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多