martes, 25 de septiembre de 2018

Pharo Script of the Day: Sort a column in a CSV file

Hi there. Today I wanted to translate to Pharo Smalltalk the code in a Bash one-liner to sort a column in a CSV file:

cat myfile.txt | cut -d \; -f 2 | sort

For replicating this one, you will need the NeoCSV package (doc), and just use the power of SortedCollection:

SortedCollection streamContents: [ : out |
 'myfile.txt' asFileReference readStreamDo: [ : in |
  (NeoCSVReader on: (ZnBufferedReadStream on: in)) in: [ : reader |
   reader 
    separator: $;;
    do: [ : each | out nextPut: each second ] ] ] ].

which you can apply to a dummy myfile.txt CSV:

a;Rachmaninoff;1
b;Horowitz;2
c;Hofmann;3
d;Scriabin;4

Hope you liked it.

0 comentarios:

Publicar un comentario