check the following script
$ cat run.sh
#!/bin/bash
echo example 1
for i in a b c; do echo "${i},"; done
echo example 2
for i in a b c; do echo "${i},"; done|sed '$s/,//'
echo example 3
for i in a b c; do echo "${i}"; done|sed '$!s/$/,/'
echo example 4
SEP=''; for i in a b c; do printf "${SEP}${i}"; SEP=',\n'; done; printf '\n'
echo example 5
STR=''; SEP=''; for i in a b c; do STR="${STR}${SEP}${i}"; SEP=,; done; echo $STR
echo example 6
echo 'a,b,c,'||sed 's/^\(.*\),\(^,\)*$/\1\2/'
echo example 7
echo 'a,b,c,'|sed 's/.\w*$//'
It gives the following output
$ . run.sh
example 1
a,
b,
c,
example 2
a,
b,
c
example 3
a,
b,
c
example 4
a,
b,
c
example 5
a,b,c
example 6
a,b,c
example 7
a,b,c
example 1: our for-loop actually produces lines. The echo $x
transforms this to a single line.
example 2: You can tell sed to process only the last line
example 3: You can tell sed to process all but the last line
example 4: you can program your for loop that you do some special processing when it is ececuted the first time: dont prepent ',\n' to the line. But in many cases you don't know when it is exectued the last time
example 5: the same as example 4 but you do not produce lines but simply a string
example 6: tell sed to remove the last occurrence of a string in a line
example 7: tell sed to remove the last non whitespace character of a line