Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 451
lindelof Avatar asked Oct 01 '08 07:10

lindelof


People also ask

How do I import a text file into MySQL?

mysql> LOAD DATA LOCAL INFILE '/path/pet. txt' INTO TABLE pet; If you created the file on Windows with an editor that uses \r\n as a line terminator, you should use this statement instead: mysql> LOAD DATA LOCAL INFILE '/path/pet.

How do I import a CSV file into MySQL?

In the Format list, select CSV. Changing format-specific options. If the csv file is delimited by a character other than a comma or if there are other specifications to the csv files, we can change it in this portion. Click Go to start importing the csv file and the data will be successfully imported into MySQL.


2 Answers

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.

like image 116
Jauco Avatar answered Sep 21 '22 17:09

Jauco


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 ','; 
like image 39
Felix Avatar answered Sep 24 '22 17:09

Felix