开发者

Looking for idiomatic way to regex-process a text file in Ruby

I'm looking for idiomatic wa开发者_如何学JAVAy to regex-process a text file in Ruby, and here's the best thing I've been able to come up with so far. It removes all " chars:

#!/usr/bin/env ruby

src_name = ARGV[0]
dest_name = ARGV[1]
File.open(src_name, "r+") { |f| 
  new_lines = f.map { |l| 
    l = l.gsub(/"/,'')
  }
  dest_file = File.new(dest_name,"w")
  new_lines.each { |l|
    dest_file.puts l
  }
}

There's got to be something better. For instance:

  • Why do I have to rewrite the file, shouldn't I be able to do something smarter with pipes?
  • I'm doing everything line-by-line, it seems like I should be able to address the problem with input and output streams.


eugen's answer is awesome. Here is the same thing as a "normal" script.

#!/usr/bin/env ruby
STDOUT << STDIN.read.gsub(/"/,'') 


If you're going for simple replacing like that, you can do it at command line like that:

ruby -e '$_.gsub!(/"/,"")' -i.bak -p INPUT_FILE.txt

It runs whatever you pass as the argument to the -e flag, replaces the content of the INPUT_FILE.txt with the result and just for safety saves a copy of the original with the .bak extension.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜