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

Hello Monks,
I like to remove the line Alias /icons/ "/ans/sttp/icons/" from the file one.txt without opening and closing the file. I mean i am looking for a perl one line command.
Input File(one.txt): Alias /ans_win/ "/ans/win/" Alias /icons/ "/ans/sttp/icons/" Alias /name/ "ans/name" Mycode: open(OH,">two.txt") or die "Could not write file two.txt"; open(FH,"one.txt") or die "Could not open file one.txt"; while(<FH>){ if (($_ =~ /Alias/) && ($_ =~ /icons/)){ print"Data=> $_\n"; }else{ print OH $_; } } close OH; close FH; $out = "mv two.txt one.txt"; system($out); My Expected output file: Alias /ans_win/ "/ans/win/" Alias /name/ "ans/name"
Can you help here please?
--Nathan

Replies are listed 'Best First'.
Re: Remove a line from a file using perl one liner
by gwadej (Chaplain) on Mar 19, 2009 at 13:54 UTC

    Look in perlrun for the -i, -e, and -n command line switches. Using these two switches and the logic from your code above, the problem is pretty easy to solve.

    perl -i -ne'print unless /Alias/ and /icons/;' one.txt

    Update: as Bloodnok points out, this could be considered dangerous. A safer version is:

    perl -i.bak -ne'print unless /Alias/ and /icons/;' one.txt

    which leaves the original as one.txt.bak.

    G. Wade
Re: Remove a line from a file using perl one liner
by Bloodnok (Vicar) on Mar 19, 2009 at 13:50 UTC
    Depends on the OS, but on *NIX,
    perl -ne 'next if m,^Alias /icons/,; print' < one.txt > tmp.txt && mv +tmp.txt one.txt
    or, if you're feeling brave...
    perl -i -ne 'next if m,^Alias /icons/,; print' one.txt
    should do the trick.

    A user level that continues to overstate my experience :-))
Re: Remove a line from a file using perl one liner
by smanicka (Scribe) on Mar 19, 2009 at 14:05 UTC
    you should be able to do an inplace edit. perl -pi -e 's/$string_to_be_removed//g' full_path/one.txt obviously if you use windows, in-place edit won't work.You can try
    #!/usr/bin/perl BEGIN {(*STDERR = *STDOUT) || die;} use diagnostics; use warnings; use strict; $| = 1; my $file = full_path/one.txt; @ARGV = $file; $^I = '~'; while (<>) { binmode ARGVOUT if $. == 1; s/$string_to_be_removed//g; print; }
    i am just trying to help.Please do check if the windows code works.I am not sure if it could throw any errors.It works fine for a substitute for me on activeperl on windows xp.I also do the replace on all files in a directory.

    -Smanicka

Re: Remove a line from a file using perl one liner
by olus (Curate) on Mar 19, 2009 at 13:56 UTC
    perl -pi -e 's#Alias.*/icons/.*##s;' one.txt
      Lines in httpd conf files are sometimes indented.
      perl -pi -e's#^\s+Alias.*/icons/.*##s' one.txt

        You're absolutely right. Thanks

        I'll go and write on the white board 'assumptions are evil' :o)

        Thanks All ...It worked well for me.
        Thanks a lot.