In our project we need to import the csv file to postgres.
There are multiple types of files meaning the length of the file changes as some files are with fewer columns and some with all of them.
We need a fast way to import this file to postgres. I want to use COPY FROM of the postgres since the speed requirement of the processing are very high(almost 150 files per minute with 20K file size each).
Since the file columns numbers are not fixed, I need to pre-process the file before I pass it to the postgres procedure. The pre-processing is simply to add extra commas in the csv for columns, which are not there in the file.
There are two options for me to preprocess the file – use python or use Sed.
My first question is, what would be the fastest way of pre-process the file?
Second question is, If I use sed how would I insert a comma after say 4th, 5th comma fields?
e.g. if file has entries like
1,23,56,we,89,2009-12-06
and I need to edit the file with final output like:
1,23,56,we,,89,,2009-12-06
Are you aware of the fact that
COPY FROMlets you specify which columns (as well as in which order they) are to be imported?Specifying directly, at the Postgres level, which columns to import and in what order, will typically be the fastest and most efficient import method.
This having been said, there is a much simpler (and portable) way of using
sed(than what has been presented in other posts) to replace an n th occurrence, e.g. replace the 4th and 5th occurrences of a comma with double commas:produces:
Notice that I replaced the rightmost fields (#5) first.
I see that you have also tagged your question as
perl-related, although you make no explicit reference toperlin the body of the question; here would be one possible implementation which gives you the flexibility of also reordering or otherwise processing fields:also produces:
Very similarly with
awk, for the record:I will leave Python to someone else. 🙂
Small note on the Perl example: I am using the
-aand-Foptions to autosplit so I have a shorter command string; however, this leaves the newline embedded in the last field ($F[5]) which is fine as long as that field doesn’t have to be reordered somewhere else. Should that situation arise, slightly more typing would be needed in order to zap the newline viachomp, thensplitby hand and finally print our own newline character\n(theawkexample above does not have this problem):EDIT (an idea inspired by Vivin):
Sorry, couldn’t resist it. 🙂