简体   繁体   中英

Ruby grep regex pattern and store it in an array

Is the highlighted section allowed in ruby ?

......
......
text = File.read(file_name)
....
....
row = text.grep(/#{Regexp.escape(line)}/g) { |log| log.split.first } 
puts "From: #{row}"
.......
......  

('line' is the variable substitution holds string values like -rr0\\hu)

I know I can use the below method to read and search a pattern in files but I have to read multiple files and check if string is present (may be in multiple lines) and get the first word of matched string's line(s).

File.open('abc.txt').grep(/rr0\hu/) { |line| line.split.first }

How can I do this in Ruby?

Use the "match" string method and loop through each line of the file

fh = File.open('/path/to/file.txt', 'r') # If there are multiple files just loop through them.
fh.each_line do |line|
     if line.match(/REGEX/) then # "match" will find the regex in each line.
          puts line.split(" ")[0] # "split" will only print the first word of the matching string line
     end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM