Skip to content

Instantly share code, notes, and snippets.

@tjsingleton
Created January 13, 2017 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjsingleton/7a63de66638f4dc737887a845285b120 to your computer and use it in GitHub Desktop.
Save tjsingleton/7a63de66638f4dc737887a845285b120 to your computer and use it in GitHub Desktop.
Reads from STDIN or a file, converts \G mysql formatted results to csv, and writes to STDOUT
require "csv"
# Reads from STDIN or a file, converts \G mysql formatted results to csv, and writes to STDOUT
#
# STDIN Usage:
# mysql ... | ruby mysql-to-csv.rb
#
# File Usage:
# ruby mysql-to-csv.rb results.txt
#
# Example Format:
# *************************** 452. row ***************************
# column_one: 1
# column_two: 123744
# column_three: 0
ROW_MARKER = /^\*+ \d+\. row \*+$/
KEY_VALUE_PAIR = /^\s*(?<key>[^:]+): (?<value>.*)$/
CSV do |csv|
first_row = true
headers = []
row = nil
ARGF.readlines.each do |line|
line.chomp!
if ROW_MARKER === line
if !headers.empty? && first_row
csv << headers
first_row = false
end
csv << row if row
row = []
next
end
if match_data = line.match(KEY_VALUE_PAIR)
headers << match_data[:key] if first_row
row << match_data[:value]
next
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment