我知道我可以在文件
中替换如下文字File.write(file, File.read(file).gsub(/text/, "text_to_replace"))
我们还可以使用sub / gsub: -
示例
root@vikas:~# cat file.txt
fix grammatical or spelling errors
clarify meaning without changing it
correct minor mistakes
add related resources or links
root@box27:~#
我想在第3行插入一些文字
root@vikas:~# cat file.txt
fix grammatical or spelling errors
clarify meaning without changing it
Hello, how are you ?
correct minor mistakes
add related resources or links
root@box27:~
示例
root@vikas:~# cat file.txt
fix grammatical or spelling errors
clarify meaning without changing it
correct minor mistakes
add related resources or links
root@box27:~#
我想搜索“小错误”并输入文字'你好,你好吗?'在那之前。
root@vikas:~# cat file.txt
fix grammatical or spelling errors
clarify meaning without changing it
Hello, how are you ?
correct minor mistakes
add related resources or links
root@box27:~
答案 0 :(得分:1)
这是答案。
File.open("file.txt", "r").each_line do |line|
if line =~ /minor mistakes/
puts "Hello, how are you ?"
end
puts "#{line}"
end
这是ruby one-liner。
ruby -pe 'puts "Hello, how are you ?" if $_ =~ /minor mistakes/' < file.txt
答案 1 :(得分:0)
您可以在像Thor这样的宝石中找到此功能。在此处查看inject_into_file
方法的文档:
http://www.rubydoc.info/github/erikhuda/thor/master/Thor/Actions#inject_into_file-instance_method。
以下是该方法的源代码:
答案 2 :(得分:0)
如果您希望在第n
行匹配(从零开始偏移):
def match_line_i(fname, linenbr regex)
IO.foreach(fname).with_index { |line,i|
return line[regex] if i==line_nbr }
end
或
return scan(regex) if i==line_nbr }
取决于您的要求。
如果您希望匹配给定的行,则返回上一行,以申请gsub
(或其他):
def return_previous_line(fname, regex)
last_line = nil
IO.foreach(fname) do |line|
line = f.readline
return last_line if line =~ regex
last_line = line
end
end
如果没有匹配,则两个方法都返回nil
。
答案 3 :(得分:0)
好的,由于sub / gsub没有这样的选项,我在这里粘贴了我的代码(对宝马代码稍作修改)以获取所有三个选项。希望这可以帮助处于类似情况的人。
在特定行号插入文字
root@box27:~# cat file.txt
fix grammatical or spelling errors
clarify meaning without changing it
correct minor mistakes
add related resources or links
always respect the original author
root@box27:~#
root@box27:~# cat ruby_script
puts "#### Insert text before a pattern"
pattern = 'minor mistakes'
File.open("file.txt", "r").each_line do |line|
puts "Hello, how are you ?" if line =~ /#{pattern}/
puts "#{line}"
end
puts "\n\n#### Insert text after a pattern"
pattern = 'meaning without'
File.open("file.txt", "r").each_line do |line|
found = 'no'
if line =~ /#{pattern}/
puts "#{line}"
puts "Hello, how are you ?"
found = 'yes'
end
puts "#{line}" if found == 'no'
end
puts "\n\n#### Insert text at a particular line"
insert_at_line = 3
line_number = 1
File.open("file.txt", "r").each_line do |line|
puts "Hello, how are you ?" if line_number == insert_at_line
line_number += 1
puts "#{line}"
end
root@box27:~#