简体   繁体   中英

perl one liner to search for a pattern

I have a text file like

Hi
how are you
<blank>
<blank>
abcd
<blank>
defgh
opqr
<blank>

I want to print all lines that have the pattern like "some text"blankblank"some text" like

how are you
<blank>
<blank>
abcd

I am thinking about using join and then search for the pattern. But I am not sure how to do it. (By blank I mean empty line)

  • Blank line: /^(?:(?!\\n)\\s)*\\n/m
  • Non-blank line: /^.*\\S.*\\n/m

So you want to print all instances of:

 /
    ^
    (?:
       .*\S.*\n
       (?: (?:(?!\n)\s)*\n ){2}
    )+
    .*\S.*\n
 /mx

As a lone liner:

 perl -0777ne'print /^(?:.*\S.*\n(?:(?:(?!\n)\s)*\n){2})+.*\S.*\n/mg' file

If all your blank lines contain no whitespace, you can simplify some:

  • Blank line: /^\\n/m
  • Non-blank line: /^.+\\n/m

 perl -0777ne'print /^(?:.+\n\n\n)+.+\n/mg' file

Perhaps I'm not understanding the question. What I think you're asking is how you can match 2 consecutive lines that have the same text ("some text") and print those.

to do that you could do something like this

assume that the file is stored as a string in $file

print "$1\n$1" while ($file =~ /(.*)(?=\n\1(?:\n|$))/mg);

.* = matches anything, grabs up as much is it can

() = capturing group, stores .* to $1 in this case

(?= ... ) = look ahead, so that that part of the string can be used in the next match

\\1 = whatever was captured in the first capturing group (ie $1)

(?: ... ) = non-capturing group

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