Convert a single line string ‘a b c’ to a multiple line string with double quotes and commas like [“a”, “b”, “c”] using bash and sed


You have single line output that contains multiple strings (could be output from a kubectl that gives all the instance names) and you want to convert it to text that can be used as the a variable enclosed by double quotes, one string on one line and separated by commas.

So having the string in a file called input.txt:

a b c

you want to convert it to the following and save it in another file called output.txt



You can use the following:

cat input.txt | tr ' ' '\n' | sed 's/^/"/g' | sed 's/$/",/g' > output.txt

which will first replace the spaces separating the strings to newlines, and then use two passes with sed, in the first adding the first quote, and the second adding the second quote and the comma.