perl - How to print 10 letters preceding every occurrence of a particular character? -


using grep, can print occurrences of uppercase letter "z" in document. output, however, display entire lines in every "z" in document found. need limit printing 10 letters appearing before every occurance of "z".

e.g., if document has line "aaaabbbbbbbbbccccccdddddddz", print "ccddddddd", 10 letters appearing before.

  • if there fewer 10 letters prior "z", nothing needs printed.
  • if "z" appears multiple times in single line, 10 letters preceding each of these "z"'s should printed, e.g.: "aaaabbbbbbbbbzcccccdddddddz" print "abbbbbbbbb" , "ccdddddddz".

the result output list of these letters, e.g.:

abbbbbbbbb ccdddddddz 

how can print 10 letters preceding every occurrence of letter "z" in document?

simple:

grep -op '.{10}(?=z)' <<< aaaabbbbbbbbbzcccccdddddddz 

explanation:

-o     : print match, not entire line -p     : use pcre / perl regex .{10}  : match 10 characters, (?=z)  : followed "z". (search positive look-ahead more details) <<< ...: here string 

edit:

note: not work, if 10 characters want overlapping. e.g. input=aaaabbbbbbbbbzdddddddz. if input contains such pattern, see igegami's answer


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -