1

I want to print all the string in the array delimited with comma

#! /bin/bash
clear
echo -e "Enter the list of hosts to print statement:\n"
readarray hosts

echo "======================================================="
echo -e "Enter the list to print"
echo "======================================================="

for i in ${hosts[@]}
do
 id="${i[@]}";echo [ ${i// /, } ]
echo $id
done

If these inputs

afrid.google.com
farid.google.com

My expected results is

[ "afrid.google.com", "farid.google.com" ]

But My result is

[ farid.google.com ]
farid.google.com
[ farid.google.com ]
farid.google.com
4
  • 2
    Your output looks like JSON, so use the jq utility. Commented Apr 15, 2019 at 18:40
  • could you please share what should i have to fill in ?? field Commented Apr 15, 2019 at 18:41
  • You don't put it in the ?? field. See the answer that someone posted. Commented Apr 15, 2019 at 18:43
  • you have 2 echo statements inside of your loop, of course you're getting 2 lines of output for each line of input! ;-) . Good luck! Commented Apr 15, 2019 at 19:59

2 Answers 2

4

Use .

$ jq -Rc '. / " "' <<< ${hosts[*]}
["afrid.google.com","farid.google.com"]
Sign up to request clarification or add additional context in comments.

Comments

0

A non jq answer, basically feeding the array through printf command with our formatting included (e.g. quotes and comma, then removing the the last chars from the string in the next command) :

hosts_str=$( printf '"%s", ' "${hosts[@]}" )
hosts_str="[ ${hosts_str: : -2} ]"
echo $hosts_str

2 Comments

Showing this error @mike afri.sh: line 14: -2: substring expression < 0
But when I try this it results the expected but with this exception, Could you advise on this hosts_str=$( printf '"%s", ' "${hosts[@]}" ) hosts_str="[ ${hosts_str} ]" echo $hosts_str Result [ "afrid.google.com ", "farid.google.com ", ] [ "afrid.google.com ", "farid.google.com ", ]

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.