Reputation: 878
I have the text file contains the below text which I need to filter based on condition.
CODE=0xea00e60c
CODE=0xea00e60d
OUTPUT="HW Address: 91183010\n,HWType:00000030\n"
CODE=0xea00e60e
CODE=0xea01ff00
If the line starts with CODE, extract everything after 0x(e.g ea00e60c) from 1st line and paste in xyz file. If the line starts with OUTPUT, extract out everything under double quotes and paste in xyz files. Sequence of extracting and putting the text in XYZ file should be maintained.
def filter_logs(filename)
postcode = "postcode_logs"
File.open(filename, 'r').each do |line|
result = (line.scan(/"(.*?)"/)) || (line.split("x")[1])
File.open(postcode, 'a') do |selected_line|
selected_line.puts(result)
end
end
end
filename and postcode is file defined already.
There is no error in code but output is also not there.
**Expected output**
ea00e60c
ea00e60d
HW Address: 91183010\n,HWType:00000030\n
ea00e60e
ea01ff00
**current output**
HW Address: 91183010\n,HWType:00000030\n
Upvotes: 1
Views: 405
Reputation: 21130
The reason this doesn't succeed is because #scan
always succeeds. If nothing is found an empty array is returned (which evaluates as truthy). Simply getting the first result should be good enough (returning nil
for empty arrays):
result = line.scan(/"(.*?)"/).first || line.split("x")[1]
Although you could also use other techniques like:
result = line[/\ACODE=0x(\h*)/, 1]
result ||= line[/\AOUTPUT="([^"]*)"/, 1]
Matching from the start of the string either CODE=0x
followed by zero or more hexadecimal characters (\h*
) capturing them in group 1 or OUTPUT="
followed by zero or more non-quote characters ([^"]*
) capturing them in group 1 followed by a "
.
Check out the regular expression documentation for Ruby if anything is unclear about the regex. Check out the documentation of the square bracket accessor of String if anything is unclear about the square bracket method usage.
Upvotes: 1