0

for example this script gives me the list of groups but each group is in a line

for group in `groups`                                                                                                   do
        echo "$group,"

done

The objective is to put them like this :group1,group2,group3. Instead of :

group1,
group2,
group3
OtO
  • 21
  • 3
  • When you call `groups` without the for loop, what is your output? Each group on a new line, or with spaces in between? – Walter A Jul 17 '21 at 21:45

4 Answers4

2

So just replace spaces with comma.

groups | tr ' ' ','
KamilCuk
  • 96,430
  • 6
  • 33
  • 74
1

Or another simple alternative is to use sed and a global substitution of ' ' with ',', e.g.

groups | sed 's/ /,/g'
David C. Rankin
  • 75,900
  • 6
  • 54
  • 79
0

You could use bash by locally changing IFS to a comma:

join() { local IFS=$1; shift; echo "$*"; }
join , $(groups)
Cole Tierney
  • 8,653
  • 1
  • 25
  • 31
0

Avoid calling another program with

my_group=$(groups)
echo "${my_group// /,}"
Walter A
  • 17,923
  • 2
  • 22
  • 40