Add quotes and new delimiter around space delimited words

regular expressionsedtext processing

I have the following string

y10_zcis y10_nom y10_infl y20_zcis y20_infl y30_zcis

I would like to transform this to

"y10_zcis", "y10_nom", "y10_infl", "y20_zcis", "y20_infl", "y30_zcis"

I accomplished something similar with the extremely ugly:

$ cat in.txt | sed 's/ /\'$'\n/g' | sed 's/\(.*\)/"\1",/g' | tr -d '\n'


"y10_zcis","y10_nom","y10_infl","y20_zcis","y20_infl","y30_zcis",

But that feels like an utter failure, and it doesn't take care of the last unwanted , (but perhaps this is best to just delete afterwards)

Best Answer

You can do

sed -e 's| |", "|g' -e 's|^|"|g' -e 's|$|"|g' in.txt

Where

  • 's| |", "|g' will replace every space with ", "
  • 's|^|"|g' while at the beginning there's no space, you must specify with ^ the beginning of the line, so you're telling, put " at the beginning.
  • 's|$|"|g' same thing but specifying the end of every line with $

UPDATE

As @don_crissti pointed out, you can do it shorter with the following

sed 's| |", "|g;s|.*|"&"|'

Where

  • ; separate each instruction
  • .* matches the entire line.
  • & an ampersand on the RHS is replaced by the entire expression matched on the LHS, in this case .*

    RHS=Right hand side

    LHS=Left hand side