在Ruby中打印匹配字符串行的第一个单词

时间:2017-05-13 07:14:57

标签: ruby

我的要求是检查特定文件夹中的任何文件中是否存在给定字符串(从文本文件中读取),如果是 存储并打印匹配字符串行的第一个单词。

以下是代码段

.......
 .......
    my_files.each do |file_name|
      puts "File Name: #{file_name}"
      content = File.read(file_name)
      changed = content.gsub( /#{Regexp.escape(id_value)}/, '' ) #'id_value' is from the first level loop ,stores string value(for every iteration).

      if content.include?("#{id_value}")
           print "its there\n"
           Row = content.split.first
           puts "From: #{Row}"
        end 

文件夹中的一个文件

CDA created on September 20th 1999
Owner: Edward Jenner
Access IDs,
id = class\234ha, class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87, class\234ha

如果id_value是 class \ 234ha

对于第一次迭代,它应该将输出设为'id'和'dept',但输出为'CDA'。此外,我也面临着以下警告。

  

test.rb:19:警告:已初始化常量Row test.rb:19:   警告:Row的先前定义来自:class \ poi23

请提出任何建议。我也寻找其他选择,但都没有用.Beginner to ruby​​如此友好地原谅我的无知。谢谢。

2 个答案:

答案 0 :(得分:0)

如果有这样的事情:

File.open(' sample.txt')。grep(/ class \ 234ha /){| line | line.split.first}  => [" id"," dept"]

将块传递给grep方法

答案 1 :(得分:0)

以下是我所拥有的脚本示例,可以满足您的需求。如果您使用文件对象的each_line方法,它会相当紧张。

#!/usr/bin/env ruby
regex_to_find = Regexp.new Regexp.escape(ARGV[0])
files = Dir.glob ARGV[1]
files.each do |f|
  current_file = File.new f
  current_file.each_line do |l|
    if l =~ regex_to_find
      puts "#{f} #{current_file.lineno}: first word = #{l.split.first}, full line: #{l}"
    end
  end
end

如果您在包含上面显示的数据的文件的目录上运行此脚本。你得到以下输出。我认为你在寻找什么。

$ ./q43950329.rb  'class\234ha' "*"
q43950329_data 4: first word = id, full line: id = class\234ha, class\poi23, class\opiuj, cap\7y6t5
q43950329_data 5: first word = dept, full line: dept = sub\6985de, ret\oiu87, class\234ha

请注意,上面的输出位于名为q43950329.rb的文件中,当前目录中存在以下文件,名为q43950329_data

CDA created on September 20th 1999
Owner: Edward Jenner
Access IDs,
id = class\234ha, class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87, class\234ha
相关问题