Searching text file and printing to new file

I'm a nearly absolute beginner to Perl, and a lot of the text
manipulation things confuse me. I have a large text file with
information essentially broken into lines like this:

findable text with a regexp
information I care about
more findable text

There are plenty of sections like this in the file. How can I write a
program that opens the file then searches for the middle line and
prints it to a new file?

0
PlagueMagazine
1/14/2008 8:47:37 PM
perl.beginners 29388 articles. 4 followers. Follow

6 Replies
640 Views

Similar Articles

[PageSpeed] 39

PlagueMagazine@gmail.com wrote:
> I'm a nearly absolute beginner to Perl,

Then this site ought to be useful: http://learn.perl.org/

> and a lot of the text manipulation things confuse me.

Really? Which things specifically, and in what way?

> I have a large text file with
> information essentially broken into lines like this:
> 
> findable text with a regexp
> information I care about
> more findable text
> 
> There are plenty of sections like this in the file. How can I write a
> program that opens the file then searches for the middle line and
> prints it to a new file?

What have you tried so far?

Example:

     open my $IN,  '<', 'infile.txt' or die $!;
     open my $OUT, '>', 'outfile.txt' or die $!
     while ( <$IN> ) {
         print $OUT scalar <$IN> if /^findable/;
     }

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
0
noreply
1/14/2008 10:08:21 PM
On Jan 14, 5:08 pm, nore...@gunnar.cc (Gunnar Hjalmarsson) wrote:
> PlagueMagaz...@gmail.com wrote:
> > I'm a nearly absolute beginner to Perl,
>
> Then this site ought to be useful:http://learn.perl.org/
>
> > and a lot of the text manipulation things confuse me.
>
> Really? Which things specifically, and in what way?
>
> > I have a large text file with
> > information essentially broken into lines like this:
>
> > findable text with a regexp
> > information I care about
> > more findable text
>
> > There are plenty of sections like this in the file. How can I write a
> > program that opens the file then searches for the middle line and
> > prints it to a new file?
>
> What have you tried so far?
>
> Example:
>
>      open my $IN,  '<', 'infile.txt' or die $!;
>      open my $OUT, '>', 'outfile.txt' or die $!
>      while ( <$IN> ) {
>          print $OUT scalar <$IN> if /^findable/;
>      }
>
> --
> Gunnar Hjalmarsson
> Email:http://www.gunnar.cc/cgi-bin/contact.pl

OK here's what I've got:

#!/usr/local/bin/perl
use strict;
use warnings;

open (OUT, ">output.txt") or die "Couldn't open output: $!";
open (IN, "input.txt") or die "Couldn't open input: $!";

while (<IN>) {
	print OUT $_;
}

close OUT;
close IN;

This (obviously) copies the whole text file. How can I select only
certain lines to copy based on either the line above or below it?

0
PlagueMagazine
1/17/2008 8:50:33 PM
PlagueMagazine@gmail.com wrote:
> On Jan 14, 5:08 pm, nore...@gunnar.cc (Gunnar Hjalmarsson) wrote:
>> PlagueMagaz...@gmail.com wrote:
>>> I have a large text file with
>>> information essentially broken into lines like this:
>>>
>>> findable text with a regexp
>>> information I care about
>>> more findable text
>>>
>>> There are plenty of sections like this in the file. How can I write a
>>> program that opens the file then searches for the middle line and
>>> prints it to a new file?
>>
>>      open my $IN,  '<', 'infile.txt' or die $!;
>>      open my $OUT, '>', 'outfile.txt' or die $!
>>      while ( <$IN> ) {
>>          print $OUT scalar <$IN> if /^findable/;
>>      }
> 
> OK here's what I've got:
> 
> #!/usr/local/bin/perl
> use strict;
> use warnings;
> 
> open (OUT, ">output.txt") or die "Couldn't open output: $!";
> open (IN, "input.txt") or die "Couldn't open input: $!";
> 
> while (<IN>) {
> 	print OUT $_;
> }
> 
> close OUT;
> close IN;
> 
> This (obviously) copies the whole text file. How can I select only
> certain lines to copy based on either the line above or below it?

I suggested a solution. Why do you ignore my suggestion and repeat your 
question?

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
0
noreply
1/18/2008 6:29:53 AM
Gunnar Hjalmarsson wrote:
> PlagueMagazine@gmail.com wrote:
>> On Jan 14, 5:08 pm, nore...@gunnar.cc (Gunnar Hjalmarsson) wrote:
>>> PlagueMagaz...@gmail.com wrote:
>>>> I have a large text file with
>>>> information essentially broken into lines like this:
>>>>
>>>> findable text with a regexp
>>>> information I care about
>>>> more findable text
>>>>
>>>> There are plenty of sections like this in the file. How can I write a
>>>> program that opens the file then searches for the middle line and
>>>> prints it to a new file?
>>>
>>>      open my $IN,  '<', 'infile.txt' or die $!;
>>>      open my $OUT, '>', 'outfile.txt' or die $!
>>>      while ( <$IN> ) {
>>>          print $OUT scalar <$IN> if /^findable/;
>>>      }
>>
>> OK here's what I've got:
>>
>> #!/usr/local/bin/perl
>> use strict;
>> use warnings;
>>
>> open (OUT, ">output.txt") or die "Couldn't open output: $!";
>> open (IN, "input.txt") or die "Couldn't open input: $!";
>>
>> while (<IN>) {
>>     print OUT $_;
>> }
>>
>> close OUT;
>> close IN;
>>
>> This (obviously) copies the whole text file. How can I select only
>> certain lines to copy based on either the line above or below it?
> 
> I suggested a solution. Why do you ignore my suggestion and repeat your 
> question?

Your suggestion didn't tell him how to solve his problem Gunnar.

A construct like the program below may help.

Rob


use strict;
use warnings;

my $wanted;

while (<DATA>) {
   if (/findable text with a regexp/) {
     $wanted = 1;
   }
   elsif (/more findable text/) {
     $wanted = undef;
   }
   elsif ($wanted) {
     print;
   }
}

__DATA__
junk
junk
junk
findable text with a regexp
information I care about
more findable text
junk
junk
junk
0
rob
1/18/2008 3:27:01 PM
On Jan 18, 10:27 am, rob.di...@350.com (Rob Dixon) wrote:
> Gunnar Hjalmarsson wrote:
> > PlagueMagaz...@gmail.com wrote:
> >> On Jan 14, 5:08 pm, nore...@gunnar.cc (Gunnar Hjalmarsson) wrote:
> >>> PlagueMagaz...@gmail.com wrote:
> >>>> I have a large text file with
> >>>> information essentially broken into lines like this:
>
> >>>> findable text with a regexp
> >>>> information I care about
> >>>> more findable text
>
> >>>> There are plenty of sections like this in the file. How can I write a
> >>>> program that opens the file then searches for the middle line and
> >>>> prints it to a new file?
>
> >>>      open my $IN,  '<', 'infile.txt' or die $!;
> >>>      open my $OUT, '>', 'outfile.txt' or die $!
> >>>      while ( <$IN> ) {
> >>>          print $OUT scalar <$IN> if /^findable/;
> >>>      }
>
> >> OK here's what I've got:
>
> >> #!/usr/local/bin/perl
> >> use strict;
> >> use warnings;
>
> >> open (OUT, ">output.txt") or die "Couldn't open output: $!";
> >> open (IN, "input.txt") or die "Couldn't open input: $!";
>
> >> while (<IN>) {
> >>     print OUT $_;
> >> }
>
> >> close OUT;
> >> close IN;
>
> >> This (obviously) copies the whole text file. How can I select only
> >> certain lines to copy based on either the line above or below it?
>
> > I suggested a solution. Why do you ignore my suggestion and repeat your
> > question?
>
> Your suggestion didn't tell him how to solve his problem Gunnar.
>
> A construct like the program below may help.
>
> Rob
>
> use strict;
> use warnings;
>
> my $wanted;
>
> while (<DATA>) {
>    if (/findable text with a regexp/) {
>      $wanted = 1;
>    }
>    elsif (/more findable text/) {
>      $wanted = undef;
>    }
>    elsif ($wanted) {
>      print;
>    }
>
> }
>
> __DATA__
> junk
> junk
> junk
> findable text with a regexp
> information I care about
> more findable text
> junk
> junk
> junk

Something like this would be a little more efficient with 1 check
statment.  I've also include File handle if you have multiple files.

#!/usr/bin/perl

use strict;
use warnings;

#put your open file here
#open (IF, "< Some file") || die "Can't open $!\n";

my $regmatch = "something 123";

while (<DATA>){

print if (/$regmatch/);

}

#close (IF);

__DATA__
123
123
123
something 123

0
000tri
1/18/2008 5:05:17 PM
Rob Dixon wrote:
> Gunnar Hjalmarsson wrote:
>> PlagueMagazine@gmail.com wrote:
>>> On Jan 14, 5:08 pm, nore...@gunnar.cc (Gunnar Hjalmarsson) wrote:
>>>>
>>>>      open my $IN,  '<', 'infile.txt' or die $!;
>>>>      open my $OUT, '>', 'outfile.txt' or die $!
>>>>      while ( <$IN> ) {
>>>>          print $OUT scalar <$IN> if /^findable/;
>>>>      }
>>>
>>> OK here's what I've got:

<code that copies the whole file snipped>

>>> This (obviously) copies the whole text file. How can I select only
>>> certain lines to copy based on either the line above or below it?
>>
>> I suggested a solution. Why do you ignore my suggestion and repeat 
>> your question?
> 
> Your suggestion didn't tell him how to solve his problem Gunnar.

Of course it did (and still does).

C:\home>type test.pl
while ( <DATA> ) {
     print scalar <DATA> if /^findable/;
}

__DATA__
junk
junk
findable text with a regexp
information I care about
more findable text
junk
junk
findable text with a regexp
more information I care about
more findable text
junk
junk

C:\home>test.pl
information I care about
more information I care about

C:\home>

> A construct like the program below may help.

<another solution snipped>

Sure, that would work too.

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
0
noreply
1/18/2008 7:16:28 PM
Reply:

Similar Artilces:

Load a Text File, Search a Text File
I'd like to load a text file that has a list of target words and replacement words. After loading the list, I'll replace all words with the target word. I've got the code worked out to do the replacing, now I just need some help with how to actually load and search the text file (xml). Here what it looks like: <dictionary> <entry> <word>Word1</word> <equivalent>Word1R1</equivalent> <equivalent>Word1R2</equivalent> <equivalent>Word1R3</equivalent> </entry> </dictionary> Th...

File Upload Problem
Hi Everyone,I was grateful to be able to download the code for uploading files into a folder from Sreedhar's web page. The code works well, but whenever there is another new file with the same file name being uploaded into the destination folder, the old file will be replaced. I am wondering if there is any way to solve this problem (How about adding a number to the new file's name, e.g. File1.doc, if there is an existing File.doc?) I am an absolute beginner and any help is deeply appreciated.The original code is as follows: <%@ Page Language="VB" MasterPageFile="~/MasterP...

Searching and printing a text file
Hi group! Ok, I'm trying to open all files in the directory containing my script, and search each one for lines containing my search string. This is my code so far: $i = 0; opendir(logdir, '.') or die "Can't open directory."; print "Enter string to search for: "; $searchstring = <>; print "\n"; #print join("\n", readdir(logdir)); print "\n"; @filelist = readdir(logdir); while($i < ($#filelist)) { open(logfile, @filelist[$i]); $i++; while(<logfile>) { #if(#####line...

to file:// or not to file://
(Firefox 1.5.0.6) I'm having trouble with HTML Anchors (links) using the file: protocol. The URL I'm trying to get at looks something like this file://///Host.Domain/Share/Dir1/Dir2/File.Ext If I click on the link, /nothing/ happens but, if I "Copy Link Location" and paste exactly the same thing into the "address bar" in FireFox, FireFox is perfectly happy to show me the file. Why the difference? Am I tripping over some security restriction here? Any suggestions? TIA, Phill W. Phill W. wrote: > (Firefox 1.5.0.6) > I'm ...

Append a text file to an existing text file
Hello, Is there a way to append a text file to an existing text file. For example, File A: Jan Feb Mar April ... File B: 10 30 40 20 ... After appending job, the File A would be like below. Jan Feb Mar April ... 10 30 40 20 ... TIA On Sep 18, 11:49=A0am, backgoo...@gmail.com (Back9) wrote: > Hello, > > Is there a way to append a text file to an existing text file. > For example, > File A: > Jan Feb Mar April ... > > File B: > 10 30 40 20 ... > > After appending job, the File A would be like below. > Jan Feb Mar April ... &g...

How to append a text file to an existing text file
Hello, Is there a way to append a text file to an existing text file. For example, File A: Jan Feb Mar April ... File B: 10 30 40 20 ... After appending job, the File A would be like below. Jan Feb Mar April ... 10 30 40 20 ... TIA Hi, It's a basic job in Perl, just open, read, and print. open B with read mode; read the content of B into memory (ie, save to a variable); close B; open A with append mode; write B's content to A; close A; 2008/9/19 Back9 <backgoodoo@gmail.com>: > Hello, > > Is there a way to append a text file to...

How to change config file for new file path of sybase files
I am a complete newbie to sybase (I'm really a microsoft sql server admin who just got a sybase db to admin). We had sybase running on one linux server and we ran out of space on that one. So, we moved the files over to a new linux server under a new filepath for the files. Now, even though I can navigate to the RUN files I can't start sybase on the new server. I'm assuming there is some config file out there that I can change the path to it to but I can't find it. Any ideas? Thanks in advance! On Fri, 18 Jul 2008 11:13:46 -0700, techgrl wrote: > I am a c...

Print and print preview file on the website without using the File
Hi everyone, Is there any source code or help I can use to print and print preview my file on the IE and print the file using my own command instead of using the IE Print command. Please do reply me. Your help is greatly appreciated. Best regards....

Access files and text files.
Hi everyone, In an attempt to create a program that will convert a text file into an access file, I figure what I need to do is read 1 line at a time from the txt and do INSERT statements to put them into the access files. I can use CREATE TABLE to create new tables and separate the data. Now, my problem is that I want to chop one big textfile into a bunch of databases based on some criteria (station id for example). How do i create a new .mdb file, that i want to be a certain name (station3.mdb for example) through code? In other words, how do i create a blank mdb file on-the-fly, that i...

Flat file and text file
can I ask are they the same? Hmm depends on where you use the word I guess. There is a slight difference: a flat file has no markup in it (e.g. a text document without formatting). Beside of flat files you have hierarchical files (e.g. XML files). These kind of files are both text files. So, in my opinion, a flat file is a text file but not every text file is a flat file (e.g. an HTML document is a text file but it isn't flat since it contains layout code).Bart De Smet [MVP] Visit www.msdn.be, www.bartdesmet.net Thanks for ur reply! I think I get wht u mean!...

read and export a csv file and tab delimited text file to new excel sheet
Hi guys,Can anyone suggest how to read and export a csv file and tab delimited text file to new excel sheet.I tried this way..but the prob is I need to know..with what kind of delimiter the file has been formatted and from the list of 20 col headers(usually first line has col headers) generally...i have to  read and get the selected col names edit and finallly rename only selected ones..and atlast...save the whole standardised file into excel file.for ex .we hav a list of 10 col headers as we see filenumber,type..etc..below.i will load all col headers in a dropdownlist first..and&n...

Query or Search the text of a text file?
Here is my problem.  I have a server that writes daily LOG files.  My task it to take a log file and be able to query or search inside that log file for any lines that contains a keyword and display them in a TextBox.  The user will also determine what that keyword is.  I am able to create a StreamReader to read the file; I don't know how to grab just the lines with that keyword.  Here is the code that I have so far.Imports System.IOImports System.DataImports System.Text.RegularExpressions Partial Class RapidRoute_RRTest2    Inherits Syst...

ANSI text file convert to Unicode text file problem
Dear all, I got a problem from my PB 7.03 ANSI version. I need to write a program to convert a ANSI text file to Unicode text file. I had been tried to use the FromANSI, toANSI, FromUnicode and ToUnicode PB function to do that. Since those functions for convert the ANSI file to Unicode file also Unicode file to ANSI file it seem working well. However, when I try to open the Unicode file (which is convert from ANSI to Unicode format by PB function) from my Wordpad, It will show me the result was fail... So now I have a question... As I know the Unicode have different type (eg. UTF-...

Problem while searching and printing data from a text file into a HTML page
hi, i have a | delimited text data file and i want a perl script which accepts an input from a textbox on a html page(search.html) and search the lines containing that string and displays them in a html page format(show.html). Any help is appreciated. the html code for search. html and show.html are. search.html <html> <head><title>Purchase Cases @ ISC</title></head> <body bgcolor="#DFD2B3"> <img src="images/purchase1.jpg"> <p><center> <table><form action="/cgi-bin/ss.cgi" method="po...

Web resources about - Searching text file and printing to new file - perl.beginners

String searching algorithm - Wikipedia, the free encyclopedia
In computer science , string searching algorithms , sometimes called string matching algorithms , are an important class of string algorithms ...

Facebook Becoming A Powerful Job Searching Tool
When most people think of a social media site that’s tailored to job searching and recruitment, the obvious answer seems to be LinkedIn . However, ...

Facebook Searching For Ways to Break Into Mobile Apps
Today’s mobile panel at the Facebook f8 developer conference was notable for the subject it didn’t cover: Facebook itself. With four panelists ...

Image Hunter - searching images on Google for iPad on the iTunes App Store
Read reviews, get customer ratings, see screenshots, and learn more about Image Hunter - searching images on Google on the App Store. Download ...

Searching - Flickr - Photo Sharing!
Advertising School: Miami Ad School, Miami Beach, USA Creative Director: Carlos Velasquez Art Director: Vanessa Castañeda Copywriter: Chris Baker ...

While searching for daughter, Va. girl's parents work to help others - YouTube
Washington Post While searching for daughter, Va. girl's parents work to help others Three months and three days. Thats how long it has been ...

Mixed martial arts searching for next generation of fighters
Chaqueal Waters is 167 centimetres tall, weighs 72 kilograms and, at just 16, he has made the decision to devote his energies to becoming the ...

Former renter searching for her mother's wedding dress from Mr Fluffy home
Robyn Elliott is moving&nbsp;on from&nbsp;the&nbsp;pain and&nbsp;dislocation caused by Canberra's Mr Fluffy asbestos crisis but more than a year ...

Family of Canadian killed while fighting ISIS in Syria still searching for answers
According to the Syrian Observatory for Human Rights, Canadian John Robert Gallagher was killed by an ISIS militant while fighting alongside ...

Family Still Searching For Answers After Christie Mullins' Cold Case Closed
The anguish is still fresh for Christie Mullins’ family, even 40 years later.

Resources last updated: 11/23/2015 10:05:23 PM