Home > database >  SED - Replace every comma outside double quotes for a newline (Bash)
SED - Replace every comma outside double quotes for a newline (Bash)

Time:12-22

I'm trying to replace all the commas outside of double quotes with a new line.

echo 'this "ok,hi",hello,how' | sed "s/,/\n/g"

The above command is resulting all the values in a new line. but, I want my sed command to give result something like

this ok,hi
hello
how

As ok,hi is enclosed in double quotes, I'm expecting them to come in a single line.

CodePudding user response:

Using sed

$ echo 'this "ok,hi",hello,how' | sed -E 's/("([^"]*)")?,/\2\n/g'
this ok,hi
hello
how

CodePudding user response:

Like this:

echo '"ok,hi","hello","how"' | sed -E 's/"([^"] )",?/\1\n/g'
ok,hi
hello
how

With awk and new string/requirements:

$ echo  'this "ok, hi",hello,how'  |
    awk -F'",' 'BEGIN{ORS=OFS="\n"} {sub(/,/, "\n", $2); print $1"\042", $2}' 

this "ok, hi"
hello
how

CodePudding user response:

If you can use gnu-awk then:

s='this "ok,hi",hello,how'

awk '{print gensub(/("([^"]*)")?,/, "\\2\n", "g")}' <<< "$s"

this ok,hi
hello
how

Another gnu-awk using FPAT:

awk -v FPAT='([^",]*"[^"]*")?[^",]*(,|$)' '{
   for (i=1; i<=NF;   i) {
      gsub(/"|,$/, "", $i)
      print $i
   }
}' <<< "$s"

this ok,hi
hello
how
  • Related