Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

copy line with character

by jalopez453 (Acolyte)
on Nov 23, 2015 at 18:32 UTC ( [id://1148413]=perlquestion: print w/replies, xml ) Need Help??

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

Hello everyone, I am looking for a little help on my code here. I want to copy the lines that have the letter M in the first column but not sure what I am doing wrong or what is missing. I am very new to perl, so I apologize for this very basic request. Thank you in advance for the help

use strict; my $find = 'M'; open (NEW, ">", "output.txt" ) or die "could not open:$!"; open (FILE, "<", "Report.txt") or die "could not open:$!"; while (<FILE>) { print NEW if (/$find/); } close (FILE); close (NEW);

Replies are listed 'Best First'.
Re: copy line with character
by stevieb (Canon) on Nov 23, 2015 at 18:41 UTC

    Hi jalopez453, welcome to the Monastery!

    When asking a question of PerlMonks, please provide us some of your sample input data, and what your expected output would look like (both in <code></code> tags as you've done with your actual code).

    I suspect what you're getting as output are all lines that contain M, but anywhere in the string, not just at the beginning. What you need to do is specify in your regex that you ONLY want to match if an M is at the start of your string. You do this by using the caret, aka ^ at the beginning of your regex:

    my $find = '^M';

    After that change is made, using this data:

    no M at start M at start M at start again another line, no M at start

    I get this output:

    M at start M at start again

      Sorry about that. For the next questions I have I will remember to include a sample of my input file. Thank you so much for the quick response this is exactly what I was wanting to accomplish!

        If you are still available, I do have another question? :) If I want to include the second line after the line containing M and wrap it all into one line on the output file what would I have to include?

        sample of input file: M12345678 John Doe 11/20/15 M987654 REJECTED FAILED --------------------------------------------- sample of output file: M12345678 John Doe 11/20/15 M987654 REJECTED FAILED use strict; my $find = '^M'; open (NEW, ">", "output.txt" ) or die "could not open:$!"; open (FILE, "<", "Report.txt") or die "could not open:$!"; while (<FILE>) { print NEW if (/$find/); } close (FILE); close (NEW);

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-24 08:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found