Bernardo Bernardo - 2 months ago 14
Linux Question

Adding quotes around a field, except for null, using sed

I'm using mysql client to export the records of a table into a CSV file. Everything works fine, except when the records have null fields.

mysql --execute="SELECT * FROM users"| sed 's/\t/","/g;s/^/"/;s/$/"/;' > users.csv


Produces

"John","Smith","john@smith.com","NULL","NULL","347-1234566"


How can I produce a result like this, where the NULL values are added to the file without the quotes around

"John","Smith","john@smith.com",NULL,NULL,"347-1234566"

Answer

Try:

mysql --execute="SELECT * FROM users"| sed 's/\t/","/g; s/^/"/; s/$/"/; s/"NULL"/NULL/g' > users.csv

The only change to your command is the addition of s/"NULL"/NULL/g.

If sed supported look-ahead or look-behind regex features, there might be more complex ways of doing this, but it doesn't have such features.

Example

With this tab-separated file as sample input:

$ cat file
John    Smith   john@smith.com  NULL    NULL    347-1234566 

You can achieve the output that you want with:

$ sed 's/\t/","/g; s/^/"/; s/$/"/; s/"NULL"/NULL/g' file
"John","Smith","john@smith.com",NULL,NULL,"347-1234566 "
Comments