replace space with delimiter in whole file -perl

Hi

I have a file which have say about 100,000 records..
the records in it look like

Some kind of text 1234567891 abcd February 14, 2008 03:58:54 AM lmnop

This is how it looks.. if u notice there is a 2byte space between each column.. and im planning to replace that with '|' ..

say ..

Some kind of text|1234567891|abcd|February 14, 2008 03:58:54 AM|lmnop

.. here is the code which i have written.. but someone should help me in completing it... thanks in advance

open(fh_tmp,"<","$chk_file");
while (my $line = <fh_tmp>)
{
$line =~ s/ /|/g ;
open(out,">>",tmpfile);
print out $line;
close(out);
}
close(fh_tmp);

please correct me if im wrong.. thanks

small correction.. there can be more than 2 byte space between 2 columns...
it should replace with delimiter '|' if it has two consecutive spaces .. not just one..

as the first column has single spaces in it "Some kind of text" .. this is one single record...
-thanks

why do you open tmpfile inside the loop? Move the open statement above the loop, close below the loop.

sed -e "s/ [ ]*/|/g" infile > outfile

there are 2 spaces between the first "/" and the "[".

i will correct the loop position..thanks for that jim...
hey sb008.. im writing a perl script.. not a shell.. but still thanks for ur suggestion.. i can use it when i do a shell ..

thanks for ur replies

open(FH_TMP,"<","$chk_file");
open(OUT,">>",tmpfile);
while (my $line = <FH_TMP>)
{
$line =~ s/ {2,}/|/g;
print OUT $line;
}
close(FH_TMP);
close(OUT);

could be done faster using perls inplace editor:

@ARGV = ($chk_file);
$^I = '.bak';
while (<>){
s/ {2,}/|/g;
print;
}

will cretae a backup of the original file first. (.bak extension)

aaaaaaaaaaaaaah, homework

if part of a larger script local-ize the global perl variables so they do not mess around with any other parts of the program that might use them (if any):

{
   local @ARGV = ($chk_file);
   local $^I = '.bak';
   while (<>){
      s/ {2,}/|/g;
      print;
   }
}

Thanks kevin.. appreciate ur replies.. will try them out.. thanks a lot...:slight_smile:

Hi,

This is the sample data i have ...

Some kind of text 1234567891 abcd February 14, 2008 03:58:54 AM 0.00 descr lmnop
Some kind of text 1234567891 abcd February 14, 2008 03:58:54 AM 0.00 lmnop
Some kind of text 1234567891 abcd February 14, 2008 03:58:54 AM 0.00

Im looking for a code that does something like this ..

Some kind of text 1234567891|abcd|February 14, 2008 03:58:54 AM|0.00|descr|lmnop
Some kind of text 1234567891|abcd|February 14, 2008 03:58:54 AM|0.00||lmnop
Some kind of text 1234567891|abcd|February 14, 2008 03:58:54 AM|0.00||

Thanks!

If the sample data is what you described previously the code I posted should work. Is the data you just now posted different? You should put code tags around your data so it retains formatting.

too funny, I would recommend sed for this too.