如何读取文件并从特定行中删除字符串

时间:2017-05-19 09:44:11

标签: ruby

我有以下文件:

ids_to_remove.txt

ID  File_Name   Row Name

id\a_po87y  GMT_dealer  auto_dev
id\ruio66   dao_wells   auto_dev
id\rzd766   123_Smart_option    cia_read
...
...
etc

GMT_dealer-details.txt

#This configuration file was written by: org.eclipse.equinox.internal

[groups]

auto_dev = id\a_po87y, id\rt7890, id\sdfs09, id\rzdo9k
qa_check = id\op9iu, id\guijm0, id\a_po87y
AD_read = id\a_po87y

dao_wells-details.txt

#Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content

[groups]

AD_read = id\a_po87y
auto_dev = id\guijm0, id\oikju8, id\ruio66
CSI = id\kiopl, id\ruio66, id\o9i8u7

ids_to_remove.txt中,有近500个条目,并且行中的项目以制表符分隔。在其他文件中,组值以空格分隔。

File_Name的值代表E:/my_files/*-details.txt处的文件夹或文件,其中*File_Name值,如GMT_dealerdao_wells,或123_Smart_option

对于每一行,我想删除IDRow Name值的任何一行,其中File_Name行包含id\a_po87y所代表的文件中的行标识auto_dev。例如,我想从文件GMT_dealer中标识为id\a_po87y的行中删除字符串auto_devqa_check只应从群组AD_read中删除,并且群组E:/my_filesfile_dir = 'E:/my_files' file = File.open("E:/ids_to_remove.txt", "r") contents = file.each_line.map { |line| line.split("\t") }.transpose id, file_name, group = contents id.each do |ids| puts "For id: #{ids}" file_name.each do |name| value = File.open("#{file_dir}/#{name}-details.txt") text = File.read(value) text.each_line do |el| group.each do |gr| if el.match(/#{gr}/) then print "group row #{gr}\n" replace = text.gsub( /#{Regexp.escape(ids)}\,\s/, '').gsub( /#{Regexp.escape(ids)}/, '' ).gsub /,\s*$/, '' end group.shift end end file_name.shift end end id.shift 中显示的相同ID应保留原样。同样,必须对For ID: id\a_po87y group row auto_dev group row auto_dev For ID: id\ruio66 For ID: id\rzd766 下的所有文件执行。

我写了下面的代码:

collectstatic

它不能满足我的需要。寻找任何建议。

对于调试添加了几个put和我得到的输出

this_wk

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

file_dir = 'E:/my_files'
file = File.open("E:/ids_to_remove.txt", "r")

file.each_line.map do |line| 
  id, file_name, group = line.split

  old_text = File.read("#{file_dir}/#{file_name}-details.txt")
  new_text = []

  old_text.each_line do |line|
    if line =~ /=/
      line_group, line_ids = line.split("=")

      if line_group.strip == group.strip
        line_ids = line_ids.split(",").reject { |l_id| l_id.strip == id }.join(",")
      end

      new_text << "#{line_group}=#{line_ids.chomp("\n")}"
    else
      new_text << line.chomp("\n")
    end

  end

  File.write("#{file_dir}/#{file_name}-details.txt", new_text.join("\n"))
end

我确信有更好的方法可以处理额外的"\n",但这会获得所需的输出。