Sed question

Matthew Seaman m.seaman at
Mon Dec 22 08:53:51 UTC 2008

Gary Kline wrote:

> 	anyway, this is one for giiorgos, or another perl wiz. i've
> 	been using the perl subsitution cmd one-liner for years with
> 	unfailing success.  is there a way of deleting lines with perl
> 	using the same idea as:
> 	  perl -pi.bak -e 's/OLDSTRING/NEWSTRING/g' file1 file2 fileN

To delete lines matching a R.E. (grep -v effectively):

    perl -ni.bak -e 'm/SOMETHING/ || print;' file1 file2 fileN

To delete lines by number from many files -- eg. exclude lines 3 to 7:

    perl -ni.bak -e 'print unless ( 3 .. 7 ); close ARGV if eof;' \
	file1 file2 fileN

The malarkey with 'close ARGV' is necessary because otherwise perl
won't reset the input line number counter ($.) for each new file.
The range expression ( N .. M ) can take matching terms rather than
line numbers, so you can also do things like:

    perl -ni.bak -e 'print unless ( m/FIRST/ .. m/SECOND/ )' \
        file1 file2 fileN



Dr Matthew J Seaman MA, D.Phil.                   7 Priory Courtyard
                                                  Flat 3
PGP:     Ramsgate
                                                  Kent, CT11 9PW

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 258 bytes
Desc: OpenPGP digital signature
Url :

More information about the freebsd-questions mailing list