Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Edit lines from a file and replace multiple lines.

by Endurance (Novice)
on Mar 26, 2019 at 05:48 UTC ( #1231692=perlquestion: print w/replies, xml ) Need Help??

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

Hello Monks,

I have a file that looks like this:

Solar system has 8 planets.

Earth is the only planet where life exists.

best part of the place is sunset.

kayak nyc nurse.

solar winds.

Colors seen in flowers are blue, pink, and purple.

name city job.

country .

Some of the other plantes are mars, jupitor and neptune.

ny.

water the plants.

solar power.

Colors seen in flowers are blue, pink, and purple.

name city job.

country.

My requirement is whenever the sentence comes "solar winds", the next 3rd line "country" should change to "place" and whenever the sentence "solar power" comes, the next 3rd line must change to "wrong line". the file has this in multiple places, multiple number of times. I have to write this in perl script. Anyone has any ideas?

  • Comment on Edit lines from a file and replace multiple lines.

Replies are listed 'Best First'.
Re: Edit lines from a file and replace multiple lines. -- basic english approach
by Discipulus (Abbot) on Mar 26, 2019 at 08:10 UTC
    hello Endurance and welcome to the monastery and to the wonderful world of perl!

    As you have seen, given scarce or absent effort will not produce code. Brother holli has shown this monastery principle, de facto.

    Formatting is important: when you compose a node her, in the bottom of the screen you can find useful links. Put your code and data input and output expected inside  <code> code tags </code>.

    As this is your first post a bit of mercy can be spent.. ;)

    While learning Perl a good principle is: are you able to do this without a computer? If yes write down the solution in basic english, then try to translate it using the syntax you are able to produce.

    Let's try:

    Open the file named file.txt. Abort if the file is unreadable. Read the file line per line. If solar wind is found annotate it's line number as solar_linenum Print line just read anyway. Read and print two lines more. If the third line has country then replace it with place and print the line but also set solar_linenum to 0. The same for the other requirement.

    Good starting points are: perlintro and the open and perlopentut then foreach ( update ..oops see here as wisely stated below AnomalousMonk) also perlvar can be handy (hint: search for $. that holds current line num while reading files.. ;).

    Never forget to begin your program with:

    use strict; use warnings; # while learning also the following can be handy; uncomment as needed: # use diagnostics; # lower case: is a pragma not a module

    HtH*

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      The code I wrote is as follows:
      #!/usr/bin/perl use strict; use warnings; my $line = ''; while (<>) { $line .= $_; if($line =~ /solar winds/) { { if( $line =~ /country/) { $line =~ s/country/place/; } } elsif($line =~ /solar power/) { { if( $line =~ /country/) { $line =~ s/country/place/; } } $line = ''; }
      This doesn't work as I dont know how to traverse to the third line and substitute the word country. Also file might have these conditions multiple times.
        Hello Endurance,

        > This doesn't work..

        ..not even compile ;) A saner indentation will help:

        use strict; use warnings; my $line = ''; while (<>) { $line .= $_; if($line =~ /solar winds/) { { if( $line =~ /country/) { $line =~ s/country/place/; } } elsif($line =~ /solar power/) { { if( $line =~ /country/) { $line =~ s/country/place/; } } $line = ''; } __END__ syntax error at endurance01.pl line 16, near "elsif" syntax error at endurance01.pl line 23, near "}" Missing right curly or square bracket at endurance01.pl line 23, at en +d of line endurance01.pl had compilation errors.

        You used too much curlys in your if statements. Then: you didnt follow my approach but instead you are adding to $line and so loosing any notion of the current line that is one of your requirements. As side note if you s/this/that/ is not needed the matching before if $x =~ /this/ because the sostitution only acts if it matches.

        But let's try to implement (partially: is your work ;) my approach:

        > Open the file named file.txt. Abort if the file is unreadable. Read the file line per line. If solar wind is found annotate it's line number as solar_linenum Print line just read anyway. Read and print two lines more. If the third line has country then replace it with place and print the line but also set solar_linenum to 0. The same for the other requirement.

        use strict; use warnings; # Open the file named file.txt. Abort if the file is unreadable. my $filename = 'file.txt'; open my $file_handle, '<', $filename or die "Unable to open the file[$ +filename]!"; # a switch to hold if solar wind is found; my $solar_wind_found_at_line = undef; # Read the file line per line. while ( my $line = <$file_handle> ){ # remove the newline chomp $line; # print is your friend! is the first and powerful debug tool.. print "DEBUG: line $. -->$line<--\n"; # check for solar wind if ( $line =~ /solar winds/){ # annotate the current line number $solar_wind_found_at_line = $.; print "DEBUG: 'solar wind' found at line $.\n"; } # if ( $solar_wind_found_at_line IS DEFINED AND THE CURERENT +LINE IS THE THIRD AFTER SOLAR WINDS ){ # REPLACE COUNTRY WITH PLACE (THIS CAN HAPPEN OR NOT) # RESET $solar_wind_found_at_line TO UNDEF (THIS MUST HAPP +EN ANYWAY) # } # at the end the expected output print "OUTPUT DESIRED: [$line]\n\n" }

        HtH

        L*

        There are no rules, there are no thumbs..
        Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Edit lines from a file and replace multiple lines.
by Laurent_R (Canon) on Mar 26, 2019 at 17:33 UTC
    Hi Endurance

    This smells like homework from thousands of miles away.

    And if any monk here does the work for you, that would really not be a favor, because you're never gonna learn anything that way.

    We most probably won't do your homework for you, but most monks will be happy to help you if you show some effort to try to solve the problem by yourself and encounter some difficulty.

    What you have to do seems to be very easy and you should presumably be able to do it by yourself even with a very basic knowledge of the Perl language. So, please, show the code that you've written and tell us what you don't succeed to do or in which respect your code fails to meet your requirement, and we will happily try to help you.

Re: Edit lines from a file and replace multiple lines.
by holli (Abbot) on Mar 26, 2019 at 06:28 UTC
    I have a lot of ideas. Doing your homework isn't one of them.


    holli

    You can lead your users to water, but alas, you cannot drown them.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1231692]
Approved by Discipulus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (1)
As of 2021-12-03 06:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (28 votes). Check out past polls.

    Notices?