Splitting a file

G

Gianni

I have a file done like this

|
|
cat
dog
monkey
troll
|
|
silver
gold
|
|
rome
london
praha
|
| etc.............

how can I create a new file after the || ??
Thanks
Gianni
 
T

Tad McClellan

Gianni said:
I have a file done like this
[snip]

how can I create a new file after the || ??


Show us what you have tried so far, and we will help you fix it.
 
J

J. Romano

I have a file done like this

|
|
cat
dog
monkey
troll
|
|
silver
gold
|
|
rome
london
praha
|
| etc.............

how can I create a new file after the || ??

Dear Gianni,

That's easy enough to do in Perl by setting the record separator
(the $/ variable) to "|\n|\n". That way, when you read in your file
the usual way, you will get records like:
cat
dog
monkey
troll
|
|

The || will still appear at the end of each record. To get rid of
those, all you have to do is call chomp on each record.

What you didn't specify is what to name each file (you didn't make
that clear). I wrote a short script for you, but since I didn't know
what to name the files, I asked the user for a file name.

One snag I ran into: Since I set the record separator to "|\n|\n"
to read in the data, I had to set it BACK to "\n" to read in the file
name from STDIN when asking the user for a file name.

My script follows. Save the script and the data after it to a file
named something like "gianni.pl" and then type "perl gianni.pl". That
should do exactly what you want.

Spero che questo ti aiuti.

-- Jean-Luc


#!/usr/bin/perl -w

use strict;

$| = 1; # autoflush for STDOUT
$/ = "|\n|\n"; # set the record separator to the two pipes

while (<DATA>)
{
# The record (including the ||) is now in $_

chomp($_); # remove the || from the record

# Skip this record if it is empty:
next if length($_) == 0;

# Ask for a file name:
print " The following lines:\n";
print $_;
print " have been found.\n";
print " Name the file you want to save them into: ";

# Get the file name from the user:
my $fileName;
{
# We want to get a new file name from STDIN,
# so we have to (temporarily) set the record
# separator back to a newline. For this, we
# use the "local" keyword:
local $/ = "\n";
$fileName = <STDIN>;
chomp($fileName); # remove the newline
}

# Write to file:
open(FILE, "> $fileName")
or die "ERROR: Cannot write to file \"$fileName\": $!\n";
print FILE $_;
close(FILE);

print "File \"$fileName\" successfully saved.\n\n";
}

__DATA__
|
|
cat
dog
monkey
troll
|
|
silver
gold
|
|
rome
london
praha
|
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top