CSV Editor Scripting

Reference for the scripts you can run in the CSV Editor.

Overview

Scripts are written in UCL and run against the table being edited, using the commands in the table module below. Anything a script prints with echo appears in the Script Output tab.

  • Rows are numbered from 0 and do not include the header.
  • Columns can be given by header name ("city") or by index (2), also from 0.
  • A script works on a copy of the table. The table is only updated if the script finishes without an error, and the whole run can be undone in one step.
  • The UCL strs, lists, itrs, fns, time, bytes and log modules are also available.

Table commands

table:header
Returns the list of header names.
table:count
Returns the number of rows.
table:get ROW COL
Returns the value of a cell.
table:set ROW COL VALUE
Sets the value of a cell.
table:row ROW
Returns a row as a hash keyed by header name. Where two columns share a name, the first is used.
table:each { |row idx| … }

Calls the block for each row, passing the row as a hash and its index.

Changing the hash does not change the table; use table:set with the index instead.

table:map-col COL { |value row| … }
Replaces each value in a column with the result of the block, which receives the current value and the row as a hash.
table:filter { |row idx| … }
Keeps only the rows for which the block returns a true value, and returns the number of rows kept.
table:add-row [VALUES]

Appends a row and returns its index.

VALUES is optional. A list fills the columns in order; a hash fills them by header name.

table:del-row ROW
Deletes a row.
table:add-col [NAME]
Appends a column and returns its index. Without a name, one like Column 4 is chosen.
table:del-col COL
Deletes a column.
table:rename-col COL NAME
Changes the header of a column.
table:sort COL [-desc]
Sorts the rows by a column. Values that are both numbers are compared numerically; anything else is compared as text.

Examples

Upper-case a column

table:map-col "name" { |v| strs:to-upper $v }

Remove rows

table:filter { |row| ne $row.city "Oslo" }

Add a calculated column

c = table:add-col "name length"
table:each { |row i|
    table:set $i $c (len $row.name)
}

Add rows

table:add-row [Dave 19 Rome]
table:add-row [city:"Bern" name:"Eve"]

Sort and report

table:sort age -desc
echo "Oldest: " (table:get 0 "name")
echo "Rows: " (table:count)