3

One of the nice features of sed is that commands (among them substitutions) can be restricted to a range of lines defined by regexp expressions (or by line number, but never mind that). Here's a simple example:

sed '/^Page 5:/,/^Page 6:/s/this/that/g'  

I was just trying to convert a rather more complex sed script to perl, and while the regexp substitutions are no problem, I realized that I don't know a straightforward way to limit substitutions to a range of lines. I can write

perl -p -e 's/^(Page 5:.*)this/$1that/g'

to change this to that on lines starting with Page 5:, but not on the lines that follow (and even on this line, despite the g it's only going to substitute once since matches are non-overlapping). Short of writing an explicit input loop and keeping track in a state variable like $inrange, isn't there a nice shortcut that can do this? This being perl, surely there must be!

4
  • 3
    perl -pe's/this/that/g if /^Page 5:/../^Page 6:/'
    – ikegami
    Apr 15, 2015 at 16:51
  • Exactly! Thanks. After reading @Sobrique's answer I came up with the one-liner syntax as well.
    – alexis
    Apr 15, 2015 at 17:13
  • PS. I'm surprised this question is (apparently) not a duplicate!
    – alexis
    Apr 16, 2015 at 13:43
  • 1
    And you can even use line numbers as well (like in sed): `perl -pe 's/this/that/g if 1../^Page 6:/' that would be from first line to the one matching Page 6. Note that perl's line index starts at 1 instead of 0 compared to sed.
    – qwertzguy
    Sep 29, 2017 at 17:52

1 Answer 1

4

There is. What you have in perl is the 'range operator'.

It goes a bit like this:

if ( m/Page 5:/ .. m/Page 6:/ ) { 
     s/this/that/g;
}

This will evaluate as 'true' if you're between the two patterns, and false otherwise.

E.g.:

use strict;
use warnings;


while (<DATA>) {
    if ( m/Page 5:/ .. m/Page 6:/ ) {
        s/this/that/g;
    }
    print;
}

__DATA__

Page 1:
this
this
more this
Page 5:
this 
this this
this
Page 6:
this 
more this
and some more this
1
  • 1
    Thanks! Yeah, that's a pretty direct translation for the simple case, which is all I need. And I can use it in one-liners with -e 's/this/that/g if (m/A/..m/B/);
    – alexis
    Apr 15, 2015 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.