0

I am new to shell scripting

I am indenting to convert a string like:

abc def ghi

to

"abc","def","ghi"

This is what I have tried:

testvar= "abc def ghi"

a='"';

res="";
coma=","
for i in $testvar
do
vals=(${i//__/ })
 if [ -z "$res" ]; then
    $res= $res$a$vals$a
 else 
 $res=$res$coma$a$vals$a
 fi
done

echo $res

Its giving this error:

$bash -f main.sh

main.sh: line 4: abc def ghi: command not found

What wrong am I doing? Is there any better way to do this?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Check out the answer to a similar questions here: https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash – Eric Jorgensen Nov 10 '18 at 15:23
  • Thanks for the pointer, but I am trying to do a bit diff thing, I have already used the split syntax from the link in vals=(${i//__/ }) – Samayra Goyal Nov 10 '18 at 15:34

2 Answers2

0

Alternate way by creating an array and using IFS. Loop through every value and add double qoutes around it.

array=($testvar)

declare item
for idx in "${!array[@]}"; do
    item="${array[$idx]}"
    array[$idx]=\""${item}"\"    # Add double qoute
done

(IFS=, ; echo "${array[*]}")   # prevents IFS from changing.
apatniv
  • 1,771
  • 10
  • 13
0

maybe you can use sed command like below: (notice that there are multi spaces in def and ghi)

$ echo 'abc def   ghi' | sed -E 's/\s+/\,/g'
abc,def,ghi
GerryLon
  • 64
  • 4