Help with formating text file

Hi,

I am fairly new to Perl  I and need some help.
I have text file that has data in this format:

           Name: Tammy Johnson
              Address 1:3803 Grenton Ave.
              City, State: Baltimore, MD
                      Zip: 21206

              Name: Ann Johnson
              Address 1:38 Park Ave.
              City, State: Baltimore, MD
                      Zip: 21206
I have to convert the data in this format (like a report)

        Name                   Address                   City,
State                    Zip
Tammy Johnson       3803 Grenton Ave        Baltimore, MD      21206
Ann Johnson            38 Park  Ave                Baltimore, MD
21206

Any help would be great!

Thanks,
Zary

0
znecheva
8/21/2002 7:26:35 PM
perl.beginners 29360 articles. 3 followers. Follow

4 Replies
322 Views

Similar Articles

[PageSpeed] 56

on Wed, 21 Aug 2002 19:26:35 GMT, znecheva@mail.pratt.lib.md.us
(Zary Necheva) wrote: 

> I have text file that has data in this format:
> 
>            Name: Tammy Johnson
>               Address 1:3803 Grenton Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206
> 
>               Name: Ann Johnson
>               Address 1:38 Park Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206
> I have to convert the data in this format (like a report)
> 
>         Name                   Address                   City,
> State                    Zip
> Tammy Johnson       3803 Grenton Ave        Baltimore, MD     
> 21206 Ann Johnson            38 Park  Ave               
> Baltimore, MD 21206

Try this:

    #! perl -w
    use strict;

    my @fields = ('Name: ', 'Address 1:', 'City, State: ', 'Zip: ');
    open IN, "<inputfile" or die "Cannot open input file: $!";
    $/ = ''; # set paragraph mode
    while (<IN>) {
        my @address = ();
        for my $f (@fields) {
            push @address, (/$f(.*)$/m ? $1 : '***unknown***');
        }
        print pack("A25" x @fields,  @address);
    }
    close IN;

-- 
felix
0
felix_geerinckx
8/22/2002 11:03:08 AM
On Wednesday, August 21, 2002, at 12:26 , Zary Necheva wrote:
[..]
>
>            Name: Tammy Johnson
>               Address 1:3803 Grenton Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206
>
>               Name: Ann Johnson
>               Address 1:38 Park Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206
> I have to convert the data in this format (like a report)
>
>         Name                   Address                   City,
> State                    Zip
> Tammy Johnson       3803 Grenton Ave        Baltimore, MD      21206
> Ann Johnson            38 Park  Ave                Baltimore, MD
> 21206

there are several ways of going at this, I personally
would recommend getting in touch with a hash structure

something on the order of

	my $count=0;
	my %address_book;
	while(<FH>) {
		next if /^\s*$/; # dump blank spaces
		chomp;
		s/^\s+//;	# strip leading spaces
		s/\s+$//;	# strip trailing spaces
		my ($tag, $value) = split(/:/);
		$count++ if ( $tag =~ /Name/) ;
		$address_book{$count}->{$tag} = $value;
	}

up to the split - it's the usual suspects -
	next if it is a blank line,
	chomp off the <CR><LF>
	remove leading and trailing blank spaces

given that your data seems to be of the form

	tag:value

why not just split it out....

I am a tad bit concerned about the 'Address 1' line there
as that implies an 'address N' but we can resolve that later.

I presume that 'Name' will define when we are looking at a
new 'address book entry'.... So I increment on that event.

then just create what an annonymous hash in the hash %address_book.

what this will allow me to do is either traverse them all later on
to find out how Many 'key types' we have in the annonymous array,
or I could just go with something simpler like

  for my $entry ( keys %address_book ) {
	print "at entry $entry\n";
	while ( my ($k, $v) = each %{$address_book{$entry}}) {
		print "\t$k -> $v\n";
	}
  }

as demonstration of a way to unpack them...

you will of course want to look at FORMAT

cf: perldoc perlform

as an alternative....

for more gory bits about this type of problem try:
http://www.wetware.com/drieux/pbl/perlTrick/HA/mo_complex.txt

if this was a homework assignment, do notice that
there is a copy right notice in the document so you
really should retain it when handing in the homework
as a derived product - you really would not want to
have the RIAA coming after you for theft of intellectual property...

ciao
drieux

---

0
drieux
8/22/2002 3:28:59 PM
here is another alternative:

#!/usr/bin/perl -w
use strict;

open(FILE,"your file") || die $!;
while(<FILE>){
        chop;
        next unless(/\S/);
        s/^\s*name://i and print "$_\t" and next;
        s/^\s*address 1://i and print "$_\t" and next;
        s/^\s*city, state://i and print "$_\t" and next;
        s/^\s*zip://i and print "$_\n";
}
close(FILE);

david

Zary Necheva wrote:

> Hi,
> 
> I am fairly new to Perl  I and need some help.
> I have text file that has data in this format:
> 
>            Name: Tammy Johnson
>               Address 1:3803 Grenton Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206
> 
>               Name: Ann Johnson
>               Address 1:38 Park Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206
> I have to convert the data in this format (like a report)
> 
>         Name                   Address                   City,
> State                    Zip
> Tammy Johnson       3803 Grenton Ave        Baltimore, MD      21206
> Ann Johnson            38 Park  Ave                Baltimore, MD
> 21206
> 
> Any help would be great!
> 
> Thanks,
> Zary

0
dzhuo
8/22/2002 5:13:05 PM
Zary Necheva wrote at Wed, 21 Aug 2002 21:26:35 +0200:

> I am fairly new to Perl  I and need some help.
> I have text file that has data in this format:
> 
>            Name: Tammy Johnson
>               Address 1:3803 Grenton Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206
> 
>               Name: Ann Johnson
>               Address 1:38 Park Ave.
>               City, State: Baltimore, MD
>                       Zip: 21206

It's strange data.
The address is written without a blank after the :,
while all other items are.

> I have to convert the data in this format (like a report)
> 
>         Name                   Address                   City,
> State                    Zip
> Tammy Johnson       3803 Grenton Ave        Baltimore, MD      21206
> Ann Johnson            38 Park  Ave                Baltimore, MD
> 21206

As TMTWTDI, here's another way:

# First, let's read the file dataset for dataset
# I assume that the datasets are seperated with a blank line
# So, let's redefine the newline seperator

local $/ = "\n\n";  # or "\r\n\r\n" on windows

local $, = "\t"; # defines the seperation character
local $\ = "\n"; # defines that every print is a println

print "Name", "Address", "City, State", "Zip";
while (<DATA>) {
  print /Name: (.*)$/m,
        /Address 1:(.*)$/m,
        /City, State: (.*)$/m,
        /Zip: (.*)$/m;
}

__DATA__
Name: Tammy Johnson
Address 1:3803 Grenton Ave.
City, State: Baltimore, MD
Zip: 21206

Name: Ann Johnson
Address 1:38 Park Ave.
City, State: Baltimore, MD
Zip: 21206


Best Wishes,
Janek

0
bigj
8/23/2002 5:03:42 AM
Reply:

Similar Artilces:

Integrating do I integrate all help files
How do I integrate PFC, sybase and powerbuilderhelp files together help such that I can get help on all issues (PFC, sybase and powerbuilderhelp ) through powerbuilder's help-content menu only . Please don't cross-post. On 1 Nov 2004 12:34:08 -0700, "Damola adesuyi" <someone@microsoft.com> wrote: >How do I integrate PFC, sybase and powerbuilderhelp files together help such >that I can get help on all issues (PFC, sybase and powerbuilderhelp ) >through powerbuilder's help-content menu only . > Bruce Armstrong [TeamSybase] http://www....

How to create and app to convert a text file into another formated text file.
Hello I'm new to the ASP forums, I have a project that I need to create and app that will convert a simple text with a ssn, firstname, lastname, etc.. With the click of the button will will convert the file to another text file but formated as firstname, lastname, ssn, etc. (I hope so far this is making sense). Anyway I have create the file upload control and a upload button to upload the text file. Now I need code for the conversion button and I'm having trouble codeing it. I just need for the button to read the text file and covert it over to new formated text file and save it. Below ...

who can tell me the format of SDF text file and CSV text file?
as title thanks On Sat, 14 Aug 1999 18:22:36 +0800, "simon" <simonshen@netease.com> wrote: >who can tell me the format of SDF text file and CSV text file? They are both text file formats used to hold data. SDF (System Data Format) - fields are fixed length. CSV (Comma Separated Values) - fields are separated by a comma Boris Gasin [TeamSybase] mailto:bgasin@dynamictechgroup.com ___ ____ _ _____ _ ____ _ ___ Dynamic Technology Group, Inc. http://www.dynamictechgroup.com/ ...

Text Formatting Problem in MultiLine Text And Reading from File
Hi, I am reading text and .cs files. And displaying them in a multiline TextBox. It works nice but when the file is loaded in .cs file then it all messed up and out of order. everything is too compact. anyidea how to solve itHighOnCodingWanna get high! solved. Had to use Environment.NewLine();HighOnCodingWanna get high! ...

Rich Text Formatting / Text Formatting Toolbar
Is there a default control in ASP.NET or in VS .NET in general that I can use to help edit textboxes and have a formatting toolbar at the top similar to the microsoft word formatting toolbar (lets you make fonts bold, select font size, font type, etc. -- basic formatting stuff and maybe insert pictures/attach files to the text box). If you reply to this message, you'll see what i'm talking about at the top of the reply box. There isn't a default one in asp.net. The one used here is called FreeTextBox. It's a free custom control that you can download. I don't think it comes with emotico...

help:about file format
------=_NextPart_000_001D_01E9FEEA.15B33820 Content-Type: text/plain; charset="gb2312" Content-Transfer-Encoding: base64 aG93IHRvIGp1ZGdlIGEgZmlsZSBpbiBkb3MgZm9ybWF0IG9yIGluIHVuaXggZm9ybWF0Pw0KdGhh bmtzIGZvciB5b3VyIHJlc3BvbnNlLg0K ------=_NextPart_000_001D_01E9FEEA.15B33820-- Billy wrote: > > how to judge a file in dos format or in unix format? > thanks for your response. Here is a somewhat simple program that will work with most files. :-) #!/usr/bin/perl use warnings; use strict; open my $fh, $ARGV[0] or die "Cannot open $ARGV[0]: $!&quo...

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...

html formatted text to formatted text in a textbox ???
hi,i have html formatted text coming from my database and i want to show it as formatted in a textbox. assigning the database text to a label works fine but getting the db content in a textbox gets the html text, not the formatted text. Ex: <b> test </b> shows as it is and i want to show a bold "test" in textbox. any ideasthank you-shane** Edited by moderator Longhorn2005 ** You will need a RTE (Rich Text Editor) such as FreeTextBox or FCKeditor to display HTML formatted text.Ryan OlshanASPInsider | Microsoft MVP, ASP.NEThttp://ryanolshan.comHow to ask a question...

HELP FORMATING A FILE
--------------08C999389F3C3A7954978482 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit HI All, I have a file from a blast report output which looks like the following: gi|12383919|gb|BF981107.1|BF981107 602310351F1 NIH_MGC_88 H... 271 4e-72 gi|12168431|gb|BF825777.1|BF825777 MR2-HN0035-171100-001-a0... 242 3e-63 Alignments >gi|12383919|gb|BF981107.1|BF981107 602310351F1 NIH_MGC_88 Homo sapiens cDNA clone IMAGE:4401421 5'. Length = 967 Score = 271 bits (694), Expect = 4e-72...

Help with text files.
Hello All, I have two files one contains entries that need to be placed in the other. With some parameters around it. 1. I have to check and make sure the entries are not already there (I did that using grep) 2. 3 of the lines I have to add need to be added in the middle of the file. (I don't know how to get them there) 3. 1 of the lines needs to be appended to a line in the orginal file. (I don't know how to do that) Can anyone point me in the right direction on this, with an example or some commands I need to learn. Thanks Michael D. Eggleton http://www.gor...

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...

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...

Help me with text files !!
Hi anyone! I have a text file that have text (or fields) separated with: "," and register separated with ENTER my question is: How I can read a register (read until de ENTER) and the most Important: How I can read a field (read until the ",") Note: 1.I want use functions in script and don�t want use pipelines. 2.I need know functions that do this. Thanks in Advance, Jose Mario Hernandez Cruz Tecnic Soport. CONSISA Consisa wrote: > > Hi anyone! > I have a text file that have text (or fields) separated with: ",&q...

Help Help Help Help Help Help
------=_NextPart_000_0074_01C2960E.EBE13A30 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Can someone please help me. I have installed mysql on Unix Solaris and it works fine I have Perl installed previously which is working and with which i have installed other perlmodules before and are working fine. I have also installed DBI and it works fine with the Sybase drivers which i have installed. When i tried to install the Msql-Mysql-modules-1.2219 drivers i get the following error. # make /usr/local/bin/perl -Iblib/arch -Iblib/lib -I/...

Web resources about - Help with formating text file - perl.beginners

Wikipedia:WikiProject Current Local City Time - Wikipedia, the free encyclopedia
This WikiProject is believed to be inactive. If you are not currently a member of the project, please consider joining it and/or its parent project ...

Wikipedia:WikiProject Current Local City Time - Wikipedia, the free encyclopedia
This WikiProject is believed to be inactive. If you are not currently a member of the project, please consider joining it and/or its parent project ...

Brooker website advert gallery
Our People Affiliations Contact Home Services About Us Positions Resume/CV formating Download an overview of our preferred resume/CV format and ...

Software - Future Shop Community Forums
Discuss software for all types of home or business applications.

AMERICAblog
skip to main skip to sidebar About us - Elections - Gay GOP Primary Schedule - Elections - Romney Economic Crisis - Jobs - TSA - Limbaugh - Fun ...

Wikiful - ARCTABLET NEWS
English (reference page) Translations to be done, your help is needed for the following languages: Korean Completed translations: French , ...

BoardGameGeek - BGG Bugs - Forum - BoardGameGeek
Register Board Games Home Recent Additions Welcome Wiki Subdomains All Abstract Games Customizable Games Children's Games Family Games Party ...

Special Character - Computer, Telephony and Electronics Glossary and Dictionary
Computer, Telephony and Electronics Glossary and Dictionary - CSGNetwork.Com's award winning online glossary of computer, telephony and electronics ...


FileBuzz - Find Software Fast
FileBuzz is your online download destination for Windows, Macintosh, Linux and PDA Freeware, Shareware and Demos.

Resources last updated: 1/23/2016 11:11:39 AM