行列転置したいことは結構あるのに、shellでやろうと思うとちょっと面倒くさい。普段はExcelで「形式を指定して貼り付け」しているけど悔しい。
- unix - Transpose a file in bash - Stack Overflow
- シェルで行列を転置 - 中川的備忘録
- AWK Users JP :: 転置行列を作る
- 行列 転置 shell script - Google 検索
ので、簡単なコマンドにした。以前作ったcsv2sqlをコピってちょっと書き換えただけ。
ソースはこちら。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env gosh | |
(use text.csv) | |
(use file.util) | |
(use gauche.parseopt) | |
(define (usage cmd) | |
(print "Usage: " (sys-basename cmd) " [option ...] <file or input>") | |
(print " h|help : Show this help") | |
(print " d|delimiter : default:<tab>") | |
(exit)) | |
(define (csv->list file :optional (delim #\tab)) | |
(port->list (make-csv-reader delim) | |
(if file | |
(open-input-file file) | |
(current-input-port)))) | |
(define (transpose m) | |
(apply map list m)) | |
(define (main args) | |
(let-args (cdr args) | |
((help "h|help" => (cut usage (car args))) | |
(delimiter "d|delimiter=s" "") | |
(else (opt . _) | |
(print "Unknown option : " opt) | |
(usage (car args))) | |
. rest) | |
(set-signal-handler! SIGINT (^ _ (exit))) | |
(let* ((delim (if (string=? "" delimiter) | |
#\tab | |
(string-ref delimiter 0))) | |
(csv (csv->list (and (not (null? rest)) | |
(car rest)) | |
delim)) | |
(writer (make-csv-writer delim))) | |
(for-each (pa$ writer (current-output-port)) | |
(transpose csv))))) |
0 件のコメント:
コメントを投稿