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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Text File Conversion iwith Perl 1

Status
Not open for further replies.

jcon11

ISP
Jul 12, 2007
4
IE
I have a very big text file in the following format; each field is seperated with a "|". Every row represents a new entry.

| |0|-|0|151| | |0|7611920|2|300|0|0|0|6830|1|16|21302|0|
| |2|-|1|0| | |0|7919120|21|400|0|0|0|6661|1|81|121|0|
..


I need to transform the file in the following format:

$1510100000160 21302 6830000 007611920
$0000100000810 121 6661000 007919120
..

some fields are included, some fields are excluded;
some fields with leading/following spaces and zeros;


Any help would be greatly appreciated.

Thanks and regards
 
some fields are included, some fields are excluded;
some fields with leading/following spaces and zeros;
Which ones? Are we supposed to guess? There are a lot of zeros in there.

Here's something to get you started, but if you need more help, you'll need to give more details.
Code:
my @input = (   '| |0|-|0|151| | |0|7611920|2|300|0|0|0|6830|1|16|21302|0|',
                ' | |2|-|1|0| | |0|7919120|21|400|0|0|0|6661|1|81|121|0|');

foreach (@input) {
    my @temp = split(/\|/, $_);
    my $output = sprintf '%04d', $temp[5];
    print $output, "\n";
}
 
Thanks for the response.

The input is from a file, the row is in reality over 5 times longer than in the sample.

I need to be able to pick out some fields, and add a specific rule to the field (add/delete spaces, leading/following zeros etc.)

Simplified Example:

| |0|-|0|151| | |0|7611920|2|300|0|0|0|6830|1|16|21302|0|

Field 5 = 151
Field 9 = 7611920
Field 10 = 2
Field 15 = 6830
Field 19 = 0

Output:
$(FIELD 5)00000(8 SPACES...)(FIELD 9)000(10 SPACES)(FIELD 15)(FIELD 19)

$15100000 7611920000 68300



Thanks and regards
 
have you tried writing any code?

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
I have tried it with printf and sprintf and it is working so far.. I can select fields and read the input from a file.
Thanks rharsh!

Code:
open(FILE, "my.data") or die("Unable to open file");
@data = <FILE>; 
close(FILE);

foreach ($data) {

my $temp = split(/\|/,$_);

my $firstfield = sprintf '%5.5s', $temp[511];

print "/$", $firstfield;

}
the array $temp[511] has the value of '210000' but I only want to display 5 numbers only '10000' instead of the '210000'

Is it possible to do that with printf/sprintf ?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top