Ruby regex gsub文本文件中的一行 [英] Ruby regex gsub a line in a text file
问题描述
我需要匹配输入的文本文件字符串中的一行,并用例如字符将捕获的行换行.
I need to match a line in an inputted text file string and wrap that captured line with a character for example.
例如,想象这样一个文本文件:
For example imagine a text file as such:
test
foo
test
bar
我想用gsub输出:
XtestX
XfooX
XtestX
XbarX
我在匹配一行时遇到了麻烦.我已经尝试过使用以^开头和以$结束的正则表达式,但是它似乎不起作用.有什么想法吗?
I'm having trouble matching a line though. I've tried using regex starting with ^ and ending with $, but it doesn't seem to work. Any ideas?
我有一个文本文件,其中包含以下内容:
I have a text file that has the following in it:
test
foo
test
bag
正在将文本文件作为命令行参数读取.
The text file is being read in as a command line argument.
我知道了
string = IO.read(ARGV[0])
string = string.gsub(/^(test)$/,'X\1X')
puts string
它输出与文本文件中完全相同的东西.
It outputs the exact same thing that is in the text file.
推荐答案
您可以像这样在一行中完成此操作:
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
默认情况下会截断给定文件,因此,如果您首先阅读文本,执行正则表达式String.gsub
,然后在块模式下使用File.open
返回结果字符串,它将一举取代文件的内容
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
)
这篇关于Ruby regex gsub文本文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!