0

Could you please help me get from

inputs='["some string", "BBB", "CCC", "something else"]'

to

inputs=( "some string" "BBB" "CCC" "something else" )

using some bash code?

Thank you.

Later Edit: The result should be a bash array. as per solutions provided by @james and @Francois, they create just a string.

Any ideas? Thanks again.

5
  • So, did you try anything? Commented Oct 2, 2016 at 10:35
  • like: echo $inputs | sed -e "s/\[/( /" -e "s/\]/ )/" ? Commented Oct 2, 2016 at 10:35
  • The solutions given will badly break in many cases. Are you actually trying to parse json? Commented Oct 2, 2016 at 13:05
  • not a json... the string inputs='["some string", "BBB", "CCC", "something else"]' comes as a result from a ruby code and what I need is to transform that string into a bash array. Commented Oct 2, 2016 at 13:07
  • 1
    can't you modify the ruby script so that it outputs the array in a more parsable format? (e.g., one string per line) Commented Oct 2, 2016 at 13:11

3 Answers 3

2

Assuming you have a variable called inputs that contains ["some string", "BBB", "CCC", "something else"], then you can use jq and mapfile:

$ mapfile -t inputs < <(jq -r '.[]' <<< "$inputs")
$ printf '<%s>' "${inputs[@]}"
<some string><BBB><CCC><something else>
Sign up to request clarification or add additional context in comments.

2 Comments

that line was just to show that spaces is respected. After running the first command (mapfile) an array called inputs will exists.
I'm stupid and you're right. Thank you very much. Is there any other way to do that without jq?
1
$ sed "s/\[/( /; s/]/ )/; s/[',]//g" foo
inputs=( "some string" "BBB" "CCC" "something else" )

First replace \[ with (, ] with ) and then ' and , with nuthin'.

1 Comment

The problem is now solved, but there's another. The resulted string is not an array anymore. If I try to make it an array with: IFS=' ' read -r -a array <<< "$inputs" I get as a result more elements as each space declares a new element. Any ideeas?
1

Simple substitution using sed

inputs=$(echo $inputs | sed -e "s/\[/( /" -e "s/\]/ )/" -e "s/,//g")

(last expression deletes the commas, overlooked it in the first attempt)

3 Comments

I got it. Thank you guys! Jean-Francois, I'll use your solution. I really appreciate!
@GabrielEnache this doesn't delete the commas though... is that okay or do you mean you were able to modify the solution to your needs?
@Sundeep: added a last expression: overlooked it (as the OP did :)). Thx.

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.