簡體   English   中英

在Ruby中打印匹配字符串行的第一個單詞

[英]Print the first word of the line of matched string in 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:警告:已初始化常量行test.rb:19:警告:Row的先前定義在此處來自:class \\ poi23

有任何建議請。 我也一直在尋找其他選擇,但都沒有用。剛開始使用紅寶石的人請原諒我的無知。

如果有這樣的事情:

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

確實將塊傳遞給grep方法

這是我所擁有的腳本的示例,可以滿足您的需求。 如果您使用文件對象的each_line方法,這是相當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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM