Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove comma from last record in a csv 1

Status
Not open for further replies.

epatton

Technical User
Aug 22, 2006
10
CA
I have a comma-separated values text file, consisting of just numbers and commas:

192123623,192123628,192123635,192123637,192123637,
192123642,192123652,192123652,192123655,192123704,
192123714,192123714,192123722,192123728,192123628,
192123749,192123824,

I want to remove the comma from the last record only (after 192123824) because this is the end of the file.

Thanks for any help you can provide,

~ Eric.
 
Thanks! That works fine. I guess I could have avoided creating a csv file with a trailing comma in the first place if I knew of a way to convert a file like this

192123623
192123628
192123635
192123637
192123637
...

into a comma-delimited file with no comma after the last record.
 
Suppose that the number of comma-delimited records in the input file is variable (usually in the hundreds). How would your script work in a general case such as this?

Thanks for your feedback!

~ Eric.
 
I should also mention that the input file is just one long string of comma-separated numbers, dozens of values long; I placed 5 values on one line in the above example so that they would fit on the screen.

~ Eric.

 
Hi

Sorry, now I am confused regarding the number of input and output columns.
Eric said:
How would your script work in a general case such as this?
Your input was 1 value in 1 line, so the [tt]awk[/tt] counted the lines :
Code:
awk '{
 printf 
  (NR>1?",":"")      [gray]# for lines after line 1 put a comma[/gray]
  (NR%5==1?"\n":"")  [gray]# for each 5th line starting from 1 put a newline[/gray]
  $0                 [gray]# put the value[/gray]
}' /input/file
But that code has a small bug : puts a newline ( \n ) before the first line. Corrected :
Code:
awk '{printf (NR>1?","(NR%5==1?"\n":""):"")$0}' /input/file

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top