ruby - Search and match string, only after a certain point in a file -
how do scan file after finding particular line. first results not count. illustration (search 3s after finding line says "begin here"):
sample file 1 3 3 4 begin here 2 3 3 1 4
the expected output 2 3s
ruby's ..
operator friend:
data.each_line |line| line.chomp! next unless (line =~ /^begin here$/) .. false puts line if line == '3' end __end__ 1 3 3 4 begin here 2 3 3 1 4
save file , run , you'll see:
3 3
..
(and much more obscure ...
) come perl, , useful particular kind of use.
what happens ..
two-state operator works if
or unless
first status line =~ /^begin here$/
in case. when status met, operator sticks, i.e., returns true until sec test matches, (returns true). 1 time happens, flip-flop starts returning false again.
in code, i'm fooling returning true, because sec test false
. in other words, code reads end of data.
..
(and ...
) really useful when you're scanning file, looking blocks of info occur throughout file. if sec conditional test found end of block, ..
reset , code skip through file until found next block start, triggered, , started capturing again.
it's people haven't seen __end__
or data
used. __end__
way tell ruby there no additional code executed beyond point. data
internal file handle points lines next __end__
, can treated io , file objects. it's useful supplying info must have script, don't want set separate file. in case i'm pretending lines after __end__
separate file. easy-peasy.
ruby
No comments:
Post a Comment