views:

943

answers:

3

I need to import largish (24MB) text files into a MySQL table. Each line looks like this:

1 1 0.008  0  0  0  0  0

There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline.

How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried

LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' ';

but MySQL will interpret a sequence of more than one space as delimiting an empty field.

Any ideas?

+6  A: 

If you're on unix/linux then you can put it through sed.

open a terminal and type:

sed 's/ \+/ /g' thefile > thefile.new

this replaces all sequences of multiple spaces with one space.

Jauco
A: 

You can also use the same command posted by Jauco to change the delimiter to ';' or \n. That would also help.

Swanand
Not really; MySQL is quite happy with spaces as field delimiters, it's only the multiple ones that are a problem here. And using LFs would make it worse as they'd then be the same as the record delimiters!
Mark Baker
A: 

Is there no way you can do this pragmatically? A simple PHP script would be able to load the file in, split by spaces, and do an insert in no time at all:

<?php

$db = mysql_connect('host', 'user', 'password')
or die('Failed to connect');
mysql_select_db('database', $db);

$fileHandle= @fopen("import.file", "r");
if ($fileHandle) {
    while (!feof($fileHandle)) {
        $rawLine = fgets($fileHandle, 4096);

        $columns = preg_split("/\s+/", $rawLine);

        //Construct and run an INSERT statement here ...   

    }
    fclose($fileHandle);
}

?>

Edit That being said, Jakal's suggestion is far neater ;)

iAn