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?
@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.
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.
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.
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).
Replace " "
with ","
:
sed 's/"[[:space:]]\+"/","/g'
Edited to catch more than one space
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 ,
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With