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

Hi all, Not sure how to achieve this problem. In a text file i need to find each line with $$$$, then edit the line after it
#something $$$$ line1 #something $$$$ line2
but the number of lines between the dollars is different. need to change line1 to name1 and line2 to name2 i guess the use of $/ is appropriate here, but need some sugestions thanks

Replies are listed 'Best First'.
Re: $/ find a line
by borisz (Canon) on Aug 10, 2004 at 11:30 UTC
    perl -i.orig -pe 'if ($c) { s/^line(\d+)/name$1/ } $c = /^\$\$\$\$$/; +' input.txt
    Boris
      rather prefer it in a script version! but i guess this is not
      while (<IN>) { $c = /^\$\$\$\$$/; if ($c) { s/^line(\d+)/name$1/ } }
        Nearly, it is: keep in mind, that you get backupfiles as filename.orig.
        BEGIN { $^I = ".orig"; } while (defined($_ = <ARGV>)) { if ($c) { s/^line(\d+)/name$1/; } $c = /^\$\$\$\$$/; print $_; }
        Boris
Re: $/ find a line
by bgreenlee (Friar) on Aug 10, 2004 at 11:27 UTC

    Just step through the file until you hit the line with $$$$, then read the next line:

    while (<>) { next if !/^\${4}/; my $next_line = <>; # do something }

    Update: Ignore this...Boris' solution below is probably closer to what you want.

    brad

Re: $/ find a line
by periapt (Hermit) on Aug 10, 2004 at 12:27 UTC
    Here is a regex solution
    use strict; use warnings; my $dataline = <<'DATALINE'; #something $$$$ line1 #something $$$$ line2 DATALINE my $dataline02 = $dataline; my $newval = 'name'; pos($dataline) = 0; while($dataline =~ /\${4}\n(\w+)\d/g){ $dataline02 =~ s/$1/$newval/; } print $dataline,"\n",$dataline02;

    PJ
    unspoken but ever present -- use strict; use warnings; use diagnostics; (if needed)
Re: $/ find a line
by wfsp (Abbot) on Aug 10, 2004 at 11:47 UTC
    A long way to do it with a loop and a flag
    #!/bin/perl5 use strict; use warnings; my $dollars; while (<DATA>){ chomp; if ($dollars){ s/^line(\d+)/name$1/; $dollars-- } print "$_\n"; $dollars++ if /\${4}/ } __DATA__ #something $$$$ line1 #something $$$$ line2