How to remove last comma?

Hi Gurus,

I have file like below:

a
b
c
d

..
I want to get

'a','b','c', 'd' 

I try to use below command to get it, but I got one extra comma

sed "s/.*/'&'/" code_LIST.txt |tr -s '\n' ","

I got below result:

'a','b','c','d',

there is one extra comma at end of the line.
How can I remove this extra comma and get result like:

'a','b','c','d'

Thanks in advance

Try

$ echo "'a','b','c','d'," | awk 'gsub(/,$/,x)'
'a','b','c','d'

OR

$ echo "'a','b','c','d'," | sed 's/,$//g'
'a','b','c','d'

OR

$ echo "'a','b','c','d'," | grep -Po '.*(?=,)'
'a','b','c','d'
1 Like
sed -n "s/.*/'&'/;1{h;d};H;\${x;s/\n/,/g;p;q}" code_LIST.txt

Emanuele

1 Like
 sed -e 's/^/\x27/;s/$/\x27/' input_file | sed -e ':a;N;$!ba;s/\n/,/g'
 perl -pe 's/^(.*)\n/\x27$1\x27,/;s/,$// if eof' input_file
1 Like

Hi,

one more awk approach.

awk -vORS="," -vs1="'" '{print s1$0s1}'  text_data1213 | sed 's/, $//g'

output will be as follows.

'a','b','c','d'

Thanks,
R. Singh

1 Like

Another awk approach:

awk '{gsub(/[a-z]/,"\x27&\x27");$1=$1}1' RS= OFS=, file
1 Like

try also:

awk '$1=$1 {printf ("\x27%s\x27\n", $0);}' RS= OFS="','" infile
1 Like
sed "s/.*/'&'/" | paste -sd, -

Regards,
Alister

2 Likes

Following may also one of the solutions.

Input file is.

a
b
c
d
paste -d"," - - - - < file_name | awk -vs1="\'" '{for(i=1;i<=NF;i++) {if(i==4) {ORS=""; print s1 $i s1} if(i!=4) {print s1 $i s1}}}' FS=, ORS=","

Output will be as follows.

'a','b','c','d'

Thanks,
R. Singh

Manual longhand using bash builtins, OSX.10.7.5...

Last login: Tue Jan 21 21:14:03 on ttys000
AMIGA:barrywalker~> text="'a','b','c','d',"
AMIGA:barrywalker~> echo "$text"
'a','b','c','d',
AMIGA:barrywalker~> text="${text:0:$[ ( ${#text} - 1 ) ]}"
AMIGA:barrywalker~> echo "$text"
'a','b','c','d'
AMIGA:barrywalker~> _

EDIT: Add the code below to simulate a file.

Last login: Tue Jan 21 21:16:30 on ttys000
AMIGA:barrywalker~> echo -n "'a','b','c','d'," > /tmp/txt
AMIGA:barrywalker~> read text < /tmp/txt
AMIGA:barrywalker~> echo "$text"
'a','b','c','d',
AMIGA:barrywalker~> text="${text:0:$[ ( ${#text} - 1 ) ]}"
AMIGA:barrywalker~> echo "$text"
'a','b','c','d'
AMIGA:barrywalker~> echo -n "$text" > /tmp/txt
AMIGA:barrywalker~> read text < /tmp/txt
AMIGA:barrywalker~> echo "$text"
'a','b','c','d'
AMIGA:barrywalker~> _

Trying to keep is neat yet readable, if its in a file, you could:-

while read line
do
   var="${var}'${line}',"
done < file

var="${var%,}"

If you prefer to build the big string another way, you can still use the last line to trim off the trailing comma if you are using ksh or bash

I hope that this helps,

Robin
Liverpool/Blackburn
UK