Home > Software design >  Bash -Convert string to list of string
Bash -Convert string to list of string

Time:02-16

In a bash i would like to convert string to list of strings , like below

Input: a,b,c Expected Output: ["a","b","c"]

Can someone please assist me with my query ?

CodePudding user response:

Use parameter expansion.

input=a,b,c
echo '["'"${input//,/'"','"'}"'"]'

It outputs:

'["' "${input//,/'"','"'}" '"]'
 ["       |                 "]
          |
          v
     here, each comma
     is replaced by ","

CodePudding user response:

Since JSON was brought up in a comment, another way using jq:

$ echo "a,b,c" | jq -Rc 'split(",")'
["a","b","c"]
  • Related