2012-08-02 152 views
21

我有一個相當大的.txt文件〜9gb,我想將這個txt文件加載到postgres中。第一行是標題,後面是所有數據。如果我postgres直接複製數據,標題將導致一個錯誤,數據類型不匹配我的postgres表,所以我需要以某種方式刪除它。如何讓Postgres Copy忽略大文本文件的第一行

樣本數據: 專案編號,MailId,MailCodeId,prospectid,listid,datemailed,金額,捐贈,拉鍊,ZIP4,VectorMajor,VectorMinor,包ID,相位,databaseid,AMOUNT2

15,53568419,89734,219906,15,2011-05-11 00:00:00,0,0,90720,2915,NonProfit,POLICY,230,3,1,0 

16,84141863,87936,164657,243,2011-03-10 00:00:00,0,0,48362,2523,NonProfit,POLICY,1507,5,1,0 

16,81442028,86632,15181625,243,2011-01-19 00:00:00,0,0,11501,2115,NonProfit,POLICY,1508,2,1,0 

雖然複製功能Postgres的有「頭」設置,可以忽略第一行,它僅適用於CSV文件:

copy training from 'C:/testCSV.csv' DELIMITER ',' csv header; 

,當我試圖在我的txt文件運行上面的代碼,它得到了一個錯誤:

copy training from 'C:/testTXTFile.txt' DELIMITER ',' csv header 
ERROR: unquoted newline found in data 
HINT: Use quoted CSV field to represent newline. 

我曾嘗試加入「引用」和「越獄」屬性,但該命令只是將似乎並不爲txt文件的工作:

copy training from 'C:/testTXTFile.txt' DELIMITER ',' csv header quote as E'"' escape as E'\\N'; 
ERROR: COPY escape must be a single one-byte character 

另外,我想過運行Java或創建一個單獨的腳手架表刪除第一行...但這些解決方案是膨脹和耗時。我將需要加載9gb的數據只是爲了刪除第一行標題......有沒有其他解決方案可以輕鬆刪除第一行的txt文件,以便我可以將數據加載到我的postgres數據庫中?

+2

的_header_選項不刪除的第一線,是需要沒有外部工具。如果這會導致「在數據中找到未加引號的換行符」,則會產生一個問題:文件的結構究竟是什麼?它與[CSV](http://en.wikipedia.org/wiki/Comma-separated_values)有什麼不同? – 2012-08-02 11:57:59

回答

38

與CSV選項使用頭選項:

WITH CSV HEADER DELIMITER AS ',' 

HEADER Specifies that the file contains a header line with the names of each column in the file. On output, the first line contains the column names from the table, and on input, the first line is ignored. This option is allowed only when using CSV format.

+0

對不起,我的misatke,CSV標頭確實有效。我的txt文件中的數據實際上與我的csv文件有不同的格式,導致了錯誤。 – thiakx 2012-08-03 09:13:13