0

i have a variable $hostgroup that has this type of content in it, that could either be

word1
word1,word2
word1,word2,word3

and so on...

what can i do to make it look like this?

"word1"
"word1","word2"
"word1","word2","word3"

basically if its one word to just add the quotes("") around it, and if there are 2+ words to also seperate them by a comma(,) and to assign the result to a new variable.

i have tried to spearate the words to multiple lines like this

echo "${hostgroup//,/$'\n'}" > hostgrp

and then try to append them to the same line again with the needed alterations

for i in $(cat hostgrp)
do
hgrp=`echo -n "\"$i\","`
done

but it just makes the ouptut look like this

"word1",
"word1 word2",
...

thanks in advance :)

syrine
  • 21
  • 3
  • 2
    Welcome to Stack Overflow. [SO is a question and answer page for professional and enthusiast programmers](https://stackoverflow.com/tour). Please add your own code to your question. You are expected to show at least the amount of research you have put into solving this question yourself. – Cyrus Mar 28 '21 at 16:28
  • As above, Even better to search for similar QA already solved, search for `[sed\ csv add quotes`. AND please read [Help On-topic](https://stackoverflow.com/Help/On-topic) and [Help How-to-ask](https://stackoverflow.com/Help/How-to-ask) before posting more Qs here. Good luck. – shellter Mar 28 '21 at 16:43
  • @shellter thanks a lot i didnt know what to look for at first. its solved. – syrine Mar 28 '21 at 16:52

2 Answers2

1

maybe something like this ?

variable_name="\"word1\",\"word2\",\"word3\""

and new lines : Trying to embed newline in a variable in bash

Mike Q
  • 5,800
  • 4
  • 48
  • 56
1
hostgrp=`echo "$hostgroup" | sed -e 's/^\|$/"/g' -e 's/,/","/g'`
echo "$hostgrp"
syrine
  • 21
  • 3