Ruby:特定行的sub / gsub或模式之前/之后

时间:2015-01-11 18:17:32

标签: ruby string design-patterns replace gsub

我知道我可以在文件

中替换如下文字
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:~

4 个答案:

答案 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)

答案 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没有这样的选项,我在这里粘贴了我的代码(对宝马代码稍作修改)以获取所有三个选项。希望这可以帮助处于类似情况的人。

  1. 在模式前插入文字
  2. 在模式之后插入文本
  3. 在特定行号插入文字

    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:~#