[英]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.