abhay180 has asked for the wisdom of the Perl Monks concerning the following question:

I am doing following:
$mod = "ABC "; $hier = `tac temp.xx | sed -n '/$mod /,/YYY/ p'| grep XXX`;
But nothing gets captured in $hier. When i execute this in shell on the same file, i get proper o/p:
%tac temp.xx | sed -n '/ABC /,/YYY/ p' | grep XXX XXX ZZZZ
What i am trrying to do: Search for a string "ABC " in the file Back track till i find "YYY" Print that line w YYY

Replies are listed 'Best First'.
Re: Sed in perl
by 1nickt (Canon) on Oct 11, 2018 at 00:40 UTC

    Hi, no sed, use Perl natively for this! It's what Perl is made for. Open the file, loop through the lines, save the last instance of YYY, print it when you find ABC.

    use strict; use warnings; my $last_seen; for my $line ( <DATA> ) { $last_seen = $line if $line =~ /YYY/; print $last_seen if $line =~ /ABC/; } __DATA__ something something YYY first something something YYY second something ABC something
    Output:
    $ perl ~/monks/1223838.pl YYY second

    Hope this helps!


    The way forward always starts with a minimal test.
      Thx!!! yes, i can do this. It would be great to understand why the sed is not working though.
        I would
        my $cmd = "tac temp.xx | sed -n '/$mod /,/YYY/ p'| grep XXX"; print "executing: '$cmd'\n"; $hier = `$cmd`; print "result: '$hier'\n";
        to actually see what's going on.
Re: Sed in perl
by SBECK (Chaplain) on Oct 11, 2018 at 12:48 UTC

    It's hard to see spaces, so I'll replace spaces with underscores for clarity.

    In your first example, it looks to me like you're doing:

       $mod = "ABC_";
       $hier = `tac temp.xx | sed -n '/$mod_/,/YYY/ p'| grep XXX`
    
    so with the substitution, your second line is actually:
       $hier = `tac temp.xx | sed -n '/ABC__/,/YYY/ p'| grep XXX`
    
    If I'm misreading the spaces, I apologize, but it appears to me that you're looking for ABC followed by 2 spaces. In the shell command, you're only looking for 1 space.