1

I have a bash script which stores some values in a variable and outputs each value on a separate line like this:

2288
87
183
30
16

I need the values to be in this format on one line so I can export to CSV:

2288, 87, 183, 30, 16

I have looked at some examples online of using sed or awk but couldn't find an example similar to mine.

Any help would be appreciated.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Steven Wilson
  • 157
  • 1
  • 3
  • 12

4 Answers4

2

paste is your friend:

$ paste -s -d',' file
2288,87,183,30,16

You can also use tr or awk, but you will get a trailing comma:

$ awk '{printf $0","}' file
2288,87,183,30,16,

$ tr -s '\n' ',' <file
2288,87,183,30,16,

Update

Its not a file its a variable I have it doesn't appear to work in the same way?

Kind of:

$ myvar="2288
87
183
30"
$ echo "$myvar" | paste -s -d','
2288,87,183,30
$ echo "$myvar" | tr -s '\n' ', ' 
2288,87,183,30,
$ echo "$myvar" | awk '{printf $0","}'
2288,87,183,30,
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Its not a file its a variable I have it doesn't appear to work in the same way? – Steven Wilson Oct 07 '13 at 14:19
  • The question wanted spaces after the commas. You could also use `echo $myvar | tr ' ' ','` to get the result without spaces (no quotes around the variable so that internal newlines are converted to spaces by the shell). Or, with spaces and commas, `echo $myvar | sed 's/ /, /g'`. This also avoids trouble if the variable contains blank lines. – Jonathan Leffler Jun 14 '22 at 16:16
1

Or you could use a bash array. Place each value into the array (I'm using a longhand version):

declare -ai nums
nums+=(2288)
nums+=(87)
nums+=(183)
nums+=(30)
nums+=(16)

oldIFS="$IFS"
IFS=','
echo "${nums[*]}"
IFS="$oldIFS"

The declare -ai declares nums as an array of integers. Then we successively append each value to the array (these could be variables). Setting IFS to a comma alters the default output separator. It also changes the default input separator as well, so it is wise to store the old value of IFS then restore it when you are done (oldIFS).

cdarke
  • 42,728
  • 8
  • 80
  • 84
1

An awk solution.

awk '{$1=$1}1' RS= OFS=,
2288,87,183,30,16

This does not give the final , that many of the solution posted here has.

Jotne
  • 40,548
  • 12
  • 51
  • 55
0

sed solution:

sed ':a;N;$!ba;s/\n/, /g' file

more detail here

Community
  • 1
  • 1
once
  • 1,369
  • 4
  • 22
  • 32