0

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 ?

2
  • What should happen to " in the input? Commented Feb 15, 2022 at 19:15
  • By "list of strings" you mean JSON? (Your sample output looks like JSON) Or a bash array? Commented Feb 15, 2022 at 19:15

2 Answers 2

1

Use parameter expansion.

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

It outputs:

'["' "${input//,/'"','"'}" '"]'
 ["       |                 "]
          |
          v
     here, each comma
     is replaced by ","
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.