0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the match method. I made some modifications to cater my requirement. thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.