Search code examples
regexperlsearch

Perl Search and Capture Line After


Alright, so this is probably a pretty easy question to answer, but I'm struggling with it. I'm trying to get my program to capture everything after a certain word and then print it. For example, if the input text is

bar foo foo foo foo

Then I want the output to be "foo foo foo foo" if I am searching for bar. I hope my question makes sense. Any help would be greatly appreciated! I'm very new to perl, so the more explanation you can give, the better. Thank you!


Solution

  • #! /usr/bin/env perl
    
    *ARGV = *DATA;  # for demo only
    
    while (<>) {
      print "line $.: $1\n" if /bar\s+(.+)/;
    }
    
    __DATA__
    you can't see me
    bar foo foo foo foo
    nope
    

    Output:

    line 2: foo foo foo foo