CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Write line to file if match

 



Alekto
Novice

Jan 9, 2010, 11:33 AM

Post #1 of 3 (471 views)
Write line to file if match Can't Post

Hi,
I was wondering how I can write a whole line from one file to another (emty)file, only if that line contains a special word.

This is what I got this far:

Code
#!/usr/bin/perl 

open (IN, "<in.txt") or die ("can't open file: in.txt");
open (OUT, ">>out.txt");

while ($line = <OUT>){

$pattern =~ m/special_word/;

if ($line == $pattern){
print NUMBER "$line\n";
}
}

close (SLOW);
close (NUMBER);


As you can see I have been trying to use regex, but I am not shure if this is the way to go...
This is how the input(in.txt) file is suppost to look like:

Code
blablablablabla..................................... 
blablablablabla.....................................
blablablablabla...........special word........
blablablablabla.....................................
blablablablabla.....................................
blablablablabla...........special word........
blablablablabla...........special word........
blablablablabla.....................................
blablablablabla.....................................
blablablablabla...........special word........
blablablablabla.....................................


Tnx!
X Alekto


FishMonger
Veteran / Moderator

Jan 9, 2010, 11:57 AM

Post #2 of 3 (467 views)
Re: [Alekto] Write line to file if match [In reply to] Can't Post

Start by adding these 2 lines just before the open statements and fix the problems that they point out.


Code
use strict; 
use warnings;



(This post was edited by FishMonger on Jan 9, 2010, 11:58 AM)


Alekto
Novice

Jan 9, 2010, 1:05 PM

Post #3 of 3 (461 views)
Re: [FishMonger] Write line to file if match [In reply to] Can't Post

Tnx!
I actually figured it out, I just added this to my while/if loop:


Code
while ($line = <IN>){ 

$match = "false";
if ($line =~ m/special_word/){
$match = "true";
print OUT "$line\t";

}
}


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives