美文网首页
如何使用Ruby删除文本文件中间的数据行

如何使用Ruby删除文本文件中间的数据行

作者: WeeverLu | 来源:发表于2020-10-21 21:22 被阅读0次

    参考:https://www.it1352.com/752703.html

    读取文件每一行,判断是否存在匹配的字符串,空格替换掉那一行

    文件内容(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"
    

    相关文章

      网友评论

          本文标题:如何使用Ruby删除文本文件中间的数据行

          本文链接:https://www.haomeiwen.com/subject/jsxymktx.html