Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can perl specify lines to change?

Status
Not open for further replies.

peterv6

Programmer
Sep 10, 2005
70
US
I'm used to using sed to change a range of lines in a file. I've found that I like to use Perl better, but I haven't been able to figure out a way to specify a range of lines to change.

In sed I can do:

sed -i '1,10 s/before/after' filename

and that will change the text only on lines 1 - 10 inclusive.

Is there a way to do the same thing in Perl? To change all lines, I'd just do:

perl -pe 's!before!after!' -i filename

Thanks....

PETERV
Syracuse, NY &
Boston, MA
 
You could use Tie::File or incorporate the input record line number variable "$." into your perl one-liner to find the range of line numbers you want to change. But as far as I know there is no built-in range argument with perl like sed apparently has.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Kevin is dead on in this. Here is the equivalent as a perl 1 liner.

perl -pe '$. < 11 && s!before!after!' -i filename

- Miller
 
Our long lost perl compatriot makes a surprise visit. Hope all is well in Millerland. :)

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Aloha mates :)

Aye, I miss y'all guys.

Just dropped by for a moment though. Back to surfing for now. Vacation never lasts as long as you'd like.

- Miller

[rainbow]
 
You can specify the range of lines to change using the .. operator.

For my windows installation:
Code:
perl -pe "s!before!after! if 1 .. 10" -i.bak filename

If either of the operands of the .. operator are constant, they are converted to integers and matched against $.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top