Ruby regex gsub a line in a text file

廉价感情. 提交于 2019-11-29 12:02:45

If you're trying to match every line, then

gsub(/^.*$/, 'X\&X')

does the trick. If you only want to match certain lines, then replace .* with whatever you need.

Update:

Replacing your gsub with mine:

string = IO.read(ARGV[0])
string = string.gsub(/^.*$/, 'X\&X')
puts string

I get:

$ gsub.rb testfile
XtestX
XfooX
XtestX
XbarX

Update 2:

As per @CodeGnome, you might try adding chomp:

IO.readlines(ARGV[0]).each do |line|
  puts "X#{line.chomp}X"
end

This works equally well for me. My understanding of ^ and $ in regular expressions was that chomping wouldn't be necessary, but maybe I'm wrong.

You can do it in one line like this:

IO.write(filepath, File.open(filepath) {|f| f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)})

IO.write truncates the given file by default, so if you read the text first, perform the regex String.gsub and return the resulting string using File.open in block mode, it will replace the file's content in one fell swoop.

I like the way this reads, but it can be written in multiple lines too of course:

IO.write(filepath, File.open(filepath) do |f|
    f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)
  end
)

string.gsub(/^(matchline)$/, 'X\1X') Uses a backreference (\1) to get the first capture group of the regex, and surround it with X

Example:

string = "test\nfoo\ntest\nbar"
string.gsub!(/^test$/, 'X\&X')
p string
=> "XtestX\nfoo\nXtestX\nbar"

If your file is input.txt, I'd do as following

File.open("input.txt") do |file|
  file.lines.each do |line|
    puts line.gsub(/^(.*)$/, 'X\1X')
  end
end
  • (.*) allows to capture any characters and makes it a variable Regexp
  • \1 in the string replacement is that captured group

If you prefer to do it in one line on the whole content, you can do it as following

 File.read("input.txt").gsub(/^(.*)$/, 'X\1X')

Chomp Line Endings

Your lines probably have newline characters. You need to handle this one way or another. For example, this works fine for me:

$ ruby -ne 'puts "X#{$_.chomp}X"' /tmp/corpus
XtestX
XfooX
XtestX
XbarX
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!