Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reverse parsing a text file

Status
Not open for further replies.

tbohon

Programmer
Apr 20, 2000
293
0
0
US
For each line of the input file, in the format

Code:
fld_1       fld_2   fld_3      fld_4
field1      field2  field3     field4

(The first line - fld_1 - is a header line and only occurs as the first line in the file.)

I want to start at the end of the line and replace the first space with a '|'. I then want to continue toward the beginning of the line putting a '|' before each field except the first one. So, in the example above, the output file would look like

Code:
field1|field2|field3|field4

I've tried a couple of different approaches but I get into nested if-end if loops and get lost.

Note that field3 is optional - it may be there or it may not be. Also, for each input file, the starting columns should be the same ... but they may change depending on variable value lengths.

Comments/hints/thoughts appreciated as always.

Tnx.

Tom

"My mind is like a steel whatchamacallit ...
 
maybe

Code:
foreach my $line (@data) {
   my @parts = split(/\s+/, $line); # split at spaces

   my $newdata;

   if (scalar(@parts) == 3) {
      # only 3 parts, so field 3 isn't there
      $newdata = join ('|',$parts[0],$parts[1],undef,$parts[3]);
   }
   else {
      $newdata = join ('|',@parts);
   }
}
 
I want to start at the end of the line and replace the first space with a '|'. I then want to continue toward the beginning of the line putting a '|' before each field except the first one. So, in the example above, the output file would look like

What is the significance of starting at the end of the line and working towards the beginning?
 
Kirsle: I'll give it a shot.

KevinADC: no particular significance, it was just an approach I was trying since I wasn't able to get a forward scan to work properly (either) :)

Thanks to both of you - will put a note back here as soon as I get a chance to test.

Best,

Tom

"My mind is like a steel whatchamacallit ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top