读取文件每一行,判断是否存在匹配的字符串,空格替换掉那一行
文件内容(test.txt
):
Person1,will,23
Person2,Richard,32
Person3,Mike,44
示例代码(test.rb
):
filename='/Users/weever/Desktop/test.txt'
puts "当前目录:"+filename
puts "处理前"
File.new(filename).each {|line| p line }
puts "处理开始"
f = File.new(filename, 'r+') #"r+" Read-write, starts at beginning of file.
f.each do |line|
if line.include?('Person2')
#seek back to the beginning of the line.
f.seek(-line.length, IO::SEEK_CUR)
#overwrite line with spaces and add a newline char
f.write(' ' * (line.length - 1))
f.write("\n")
end
end
f.close
puts "处理结束"
File.new(filename).each {|line| p line }
ruby test.rb
执行结果:
当前目录:/Users/weever/Desktop/test.txt
处理前
"12343\n"
"345678\n"
"90-=\n"
"76\n"
"\n"
"Person1,will,23\n"
"Person2,Richard,32\n"
"Person3,Mike,44"
处理开始
处理结束
"12343\n"
"345678\n"
"90-=\n"
"76\n"
"\n"
"Person1,will,23\n"
" \n"
"Person3,Mike,44"
网友评论