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

Dear monks how can i delete or replace a portion of a line from a simple text file!?
Antonis

Replies are listed 'Best First'.
Re: delete a line
by jmcnamara (Monsignor) on Jan 17, 2003 at 12:52 UTC

    Here are some one-liners to delete a line or replace a portion of a line in a file. The command line options are explained in perlrun
    # Remove the third line in the file perl -i.bak -ne 'print unless $. == 3' file # Remove any lines that contain foo perl -i.bak -ne 'print unless /foo/' file # Remove foo from all lines perl -i.bak -pe 's/foo//g' file # Substitute foo with bar on all lines perl -i.bak -pe 's/foo/bar/g' file
    The -i.bak option makes the changes in-place and saves a back-up to file.bak. If you are sure that your filter is correct you can omit the .bak part and skip the backup (use with care).

    --
    John.

Re: delete a line
by broquaint (Abbot) on Jan 17, 2003 at 12:19 UTC
    I'd recommend Dominus' wonderful Tie::File for line-based file manipulation needs, or perhaps the -i switch would be more appropriate (see. the perlrun manpage for more info).
    HTH

    _________
    broquaint

Re: delete a line
by virtualsue (Vicar) on Jan 17, 2003 at 12:40 UTC
    Try looking in Perl FAQ: Files and formats. The second item in the list explains simple file manipulation such as adding & deleting a line in a file very well. I suggest you browse through the entire category.
(jeffa) Re: delete a line
by jeffa (Bishop) on Jan 17, 2003 at 23:00 UTC
    Closely related to deleting a line is deleting a group of lines between two delimiters. Such cases are easily solved with perl's "flip flop" operator. The following code will not print out the lines between (and including) SKIP and CONTINUE:
    use strict; use warnings; while (<DATA>) { print unless /^SKIP\s$/ .. /^CONTINUE\s$/; } __DATA__ one two SKIP THOUGH THEY DAYS ARE FEW, THEY'RE FILLED WITH TEARS, AND SINCE I LOST YOU IT FEELS LIKE YEARS. YES, IT SEEMS SO LONG GIRL, SINCE YOU'VE BEEN GONE, AND I JUST CAN'T GO ON IF YOU WON'T SEE ME, (you won't see me) YOU WON'T SEE ME. (you won't see me) © Northern Songs Ltd CONTINUE buckle my show (sic)
    Read perlop to find out more about the flip flop feature of the range operator.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)