Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed Pattern to Insert Comma between double Quotes

Tags:

bash

shell

unix

sed

I am very new to sed Regex pattern and stuck with a requirement. I have few Records which i am pulling from Database

"Name" "Age" "From ABC" "12"

now I am exporting it to CSV with Comma Separated i am using 's/[[:space:]]\+/,/g' This Regex

Which is giving me the Result as

"Name","Age","From,ABC","12"

Which is fine except the Third Column where it has inserted , for space now i want to insert , in between double quotes.

Can any One Guide me for the same?

With 's/"[[:space:]]\+"/","/g' Regex i Am able to get "Name","Age","From,ABC","12" But its is failing when i have "Name","","From,ABC","12" it gives "Name",",","From,ABC","12"

Is there any other way to counter this?

like image 661
Anupam Alok Avatar asked Feb 08 '18 16:02

Anupam Alok


People also ask

Does sed work with double quotes?

@DummyHead Here's another approach: if you use single quotes, the sed command is exactly as you type it. If you use double quotes, you must take into account all shell substitutions and elaborations to "visualize" what command is eventually passed on to sed.

How do you use sed multiple times?

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.

How do you add a double quote to a string in Unix?

You can't use double quotation within another double quotation to assign any string value. If you want to print double quote in the output then you have to use the backslash (\) with the string.

How do you insert a double quote in a text file?

If we want to insert double quotes into a file we can do this by specifying Chr(34); the Chr function takes the ASCII value – 34 – and converts it to an actual character (in this case double quotes).


2 Answers

Replace " " with ",":

sed 's/"[[:space:]]\+"/","/g'

Edited to catch more than one space

like image 122
match Avatar answered Sep 25 '22 16:09

match


I'd do this:

echo \"Name\"     \"Age\" \"From ABC\" \"12\" | sed -e 's/"[[:space:]]\+"/","/g'

which returns

"Name","Age","From ABC","12"

edit

if you want have empty strings " " also matched, then you could do this:

$ echo \"Name\" \" \"    \"Age\" \"From ABC\" \"12\" | sed -e 's/\("[[:alnum:][:space:]]*"\)/\1,/g' \
    -e 's/",[[:space:]]\+/",/g' \
    -e 's/,[[:space:]]\?$//g'

which returns

"Name"," ","Age","From ABC","12"

The first rules matches strings in quotes (that also may be empty), the second rule removes the spaces between , and the next ", the third rules removes the last ,.

like image 28
Pablo Avatar answered Sep 24 '22 16:09

Pablo