4

I have some words separated by commas in a file, such as below:

variable1, variable2, variable3, variable4

What's the easiest way to use BASH for adding quotation marks to each word?

The end result should look like:

"variable1", "variable2", "variable3", "variable4"
Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
jitter
  • 51
  • 1
  • 3

2 Answers2

7

Simply with sed:

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

The output:

"variable1", "variable2", "variable3", "variable4"
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

It can be done with parameter expansion

str="variable1, variable2, variable3, variable4"
str2=\""${str//, /\", \"}"\"

echo "$str2"

however to have a csv format, double quotes should be just before the comma without space, the reason of double quotes may be to allow , inside a field but if field already contains a comma the quoting must be done before.

Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36