Re: Strip trailing commas
Posted in 1998
cl3071@sbc.com wrote: > > I am trying to write a ksh function that will take values from an input file, > in a collumn or one line, and concatinate them into one line with comma > seperators. The problem is, how do I truncate the trailing comma? i.e.: > > input: 11 > 22 > 33 > > output: 11,22,33 > > so far I have > > cat file.dat | nawk -v LINE=$line 'BEGIN { FS=",";ORS=",";OFS=","} > { > for ( i=1;i<=NF;i++) > {print $i}}' > > this gives the output: > 11,22,33, > > Even if the input is already in a single line. > > How do I strip that darn last comma? I tend to do this rather differently -- I regard the output as a sequence of numbers where all except the first are preceded by a comma: pad = ""; for (i=1;i<=NF;i++) { printf "%s%d", pad, $i; pad = ","; } The advantage of this is that I know exactly when I'm dealing with the first element; I don't have to know in advance when I'm dealing with the last element. Thus, it is better suited to while loops than some other techniques. -- Jonathan Leffler (jleffler@informix.com, jleffler@earthlink.net) Guardian of DBD::Informix v0.60 -- see http://www.perl.com/CPAN #include <disclaimer.h>