はじめに
年寄りなのでスプレッドシートでテーブルを編集してブログやGitHub、課題管理システム(Backlogとか)に貼り付けることがけっこうあるのですが、今まではスプレッドシートからコピーして、GitHubの適当なテキストエリアに貼り付けするとマークダウンに変換してくれるのを利用して変換をしていました。しかし冬休みともなるとGitHubのページを開いてあるタブもなく、わざわざ開くのも手間なのでスクリプトにしました(本文ここまで)
コード
#!/usr/bin/env ruby
class String
# 文字列の末尾のスペースを削除してsepで分割する
def split_to_cols(sep="\t")
strip.split(sep)
end
end
class Array
# markdownの行に変換する
def to_mkdown_cells
join(" | ")
end
end
class TablePrinter
def initialize(header)
@header = header.split_to_cols
@widths = @header.map {|c| c.size }
end
# ヘッダー行を表示する
def header
puts @header.to_mkdown_cells
puts @widths.map {|w| "-"*w}.to_mkdown_cells
end
# lineを行として表示する
def row(line)
# 文字列をセルに分割してヘッダーの幅にあわせてパディング
cells = line&.split_to_cols.map.with_index{ |c, i| sprintf("% -#{@widths[i]}s", c)}
puts cells.to_mkdown_cells
end
end
# 先頭をヘッダーとして表示
table = TablePrinter.new(ARGF.gets)
table.header
# 以降はボディとして表示する
while row = ARGF.gets
table.row(row)
end
実行してみる
手抜きしてセルの幅をヘッダーにあわせているので長いセルがあると崩れるのはご愛敬です。
echo -e "Name\tValue\nabc\tefg\nfoo\tbar\nlooooooooooooong \t line" | t2mkdown
Name | Value
---- | -----
abc | efg
foo | bar
looooooooooooong | line
まとめ
重宝しそうな気がしています。