0

I'm trying to insert a CSV file into a PSQL table using a bash script. My first aim is parsing the CSV file then insert the datas, row by row. COPY command is not convenient for me. I've used the following script but it doesn't worked.

Edit: I didn't create the table by the way. Should I?

#!/bin/sh             
    while IFS=, read col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11 col12
    do
        echo "INSERT INTO table_name ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l") VALUES ('$col1','$col2','$col3','$col4','$col5','$col6','$col7','$col8','$col9','$col10','$col11','$col12');"
    done < ppr.csv | sudo psql -U pg_user -d test;
6
  • Could you provide more informations about your problem ? You say "It does not work", so what happen when it does not work ? Do you have any errors ? Commented Feb 12, 2020 at 11:09
  • ERROR: relation "table_name" does not exist at character 13 LINE 1: INSERT INTO table_name (a, b, c, d, e, f, g, h, i, j, k, l) VALUES .. Commented Feb 12, 2020 at 11:32
  • 1
    Try using single quotes for the field names or escaping the double ones. Commented Feb 12, 2020 at 11:34
  • @Poshi - ERROR: syntax error at or near "'a'" at character 18 after single quotes. Commented Feb 12, 2020 at 11:36
  • You should escape inner double quotation symbols. Commented Feb 12, 2020 at 12:38

2 Answers 2

1

Don't try to parse CSV with bash, that would be quite hard to get right.

You should use file_fdw to define a foreign table in the database. That allows you to access the data from the database without actually loading it. In a way, you turn PostgreSQL into a CSV parser.

Then you can select from that foreign table like from a normal table and for example insert parts of it into a proper PostgreSQL table.

Sign up to request clarification or add additional context in comments.

Comments

0

You should escape inner double quotation marks :

#!/bin/sh             
while IFS=, read col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11 col12
do
    echo "INSERT INTO table_name (\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\") VALUES ('$col1','$col2','$col3','$col4','$col5','$col6','$col7','$col8','$col9','$col10','$col11','$col12');"
done < ppr.csv | sudo psql -U pg_user -d test;

3 Comments

ERROR: relation "table_name" does not exist LINE 1: INSERT INTO table_name. Should I create the table and columns first or ?
@Bertug Yes you should
Your solution won't work if any of the values contain a single quote. Also, that does not account for quoted fields.

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.