Command to replace newline with comma

Hi Experts,

I need an urgent help in replacing newline characters in my single column file by a comma.

I am using following command for this purpose:

sed -n -e 'H;${x;s/\n/,/g;s/^,//;p;}' parameter.rtf | rev | cut -c 4- | rev

My input file has:

TABLE_1
TABLE_2
TABLE_3

What I need:

TABLE_1,TABLE_2,TABLE_3

What I am getting:

TABLE_1,TABLE_2,TABLE_3,

I want to avoid that last comma after TABLE_3 which is coming since there is a newline character at the end of the file. I am not sure whether the file will always have that newline char at the end of file so I need to be sure it doesnt blindly trims the last char but removes it only if it is a comma.

Can you please suggest a solution for this?

Regards,
Newbie

try:

awk '$1=$1' RS= OFS=, infile

Using sed,

sed ':a;N;$!ba;s/\n/,/g'
1 Like
sed -n -e '1h;1!H;${x;s/\n/,/g;p;}' parameter.rtf

Solution from the previous post seems elegant; Unix sed needs

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

A simple solution using paste:

$ paste -sd, file
TABLE_1,TABLE_2,TABLE_3

Thanks a lot guys. It helped!!!

Now an addition to it:
TABLE_1
TABLE_2
TABLE_3
are transposed as TABLE_1,TABLE_2,TABLE_3

Now I need it as 'TABLE_1','TABLE_2','TABLE_3'
Again to make sure the last character is not a comma.

Appreciate your support.

Cheers,
NG

Try

$ cat file
TABLE_1
TABLE_2
TABLE_3 
$ awk '{x=(NR==1)?"\x27"$0"\x27":x OFS "\x27"$0"\x27"}END{print x}' OFS=, file

Resulting

'TABLE_1','TABLE_2','TABLE_3'

Same approach, written in a different way:

awk '{s=s (s?OFS:x) q $0 q} END{print s}' q=\' OFS=, file
1 Like

With sed ( not so nice :frowning: )

sed -e "s/^/\'/;s/$/\'/" INPUT_FILE | sed -e ':a;N;$!ba;s/\n/,/g'
sed -n -e '1{s/^/'\''/;h;}' -e '1!H;${x;s/\n/'\'','\''/g;s/$/'\''/;p;}'

or

sed -e ':a' -e 'N;$!ba' -e 's/\n/'\'','\''/g;s/^/'\''/;s/$/'\''/'

Another sed:

sed -n "s/.*/'&'/"'; 1h; 1!H; $g; $s/\n/,/gp' file
1 Like

Cool:cool:, it's of course simpler. And also works around the :mad:history:mad: in interactive bash.