4

I am trying to import data into my postgres table using \copy from a CSV file The data is as follows:

1,2,"First Line \n Second Line", "Some other data"

My motive is to preserve '\n' while importing the data.

The following works:

insert into table (col1, col2, col3, col4) values (1, 2, E'First Line \n Second Line', 'Some other data')

But how do I achieve the same result using \copy command?

0

2 Answers 2

8

The only thing you can escape in CSV is the field delimiter (" by default) which you escape by doubling it.

Line breaks cannot be escaped, and indeed it is not necessary, as you can just use a literal line break.

This is a single line in CSV:

1,2,"First Line
Second Line", "Some other data"
Sign up to request clarification or add additional context in comments.

2 Comments

I was kind of afraid I'll have to do that in the end. :/ Just a little side help, how to I export Excel data to csv with newlines?
I would like to help, but I don't know Excel. You can always use COPY ... FROM PROGRAM 'command' and substitute a command that massages the CSV file for you.
1

I'm afraid you have to modify your csv to backslash \n you want to preserve

b=# copy t from stdout;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> "First Line \n Second Line"
>> "First Line \\n Second Line"
>> \.
COPY 2
b=# select * from t;
              a
-----------------------------
 "First Line                +
  Second Line"
 "First Line \n Second Line"
(2 rows)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.