How do I import a whitespace-delimited text file into MySQL?
Asked Answered
V

4

5

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?

Vermont answered 1/10, 2008 at 7:13 Comment(0)
C
10

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.

Cnidoblast answered 1/10, 2008 at 7:19 Comment(0)
D
2

If you're on Windows, just use Excel.

Excel will import a whitespace-delimited file (check the 'treat subsequent delimiters as one' box from the import menu).

Then you can simply save the file as a CSV from Excel and import into MySQL using:

LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ','; 
Demarco answered 28/3, 2011 at 17:44 Comment(0)
I
0

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

Inhospitality answered 1/10, 2008 at 7:26 Comment(1)
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!Glandular
M
0

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 ;)

Merow answered 1/10, 2008 at 7:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.