tacコマンド

昇順に並んでいるデータを降順に並べ替えたい。しかもデータはファイルに1行ずつ入ってる。

というような時に tac コマンドが便利。がOS Xには入ってないmacportで検索しても引っかからない。と思っていたら、coreutils パッケージに入ってるらしい。

$sudo port install coreutils

で入るけど、tacコマンドが見つからない。PATHが通ってないのかとか思ったのだが、GNU由来のコマンドはgがつくらしく、 gtac らしい。OS Xにもともと入っているtail コマンドでも同じ事ができる tail -r file で可能。

しかし日本語訳されているマニュアルなどを読むとtail -rは大きいファイルには向かないし、GNU版には無いからやめろとか書いてあったりする。

MAN tail http://www.linux.or.jp/JM/html/gnumaniak/man1/tail.1.html

せっかくなので比較してみた。tacの方が速い。何回かやらないと正確には分からない訳だが。tail -rで大きいファイルを並べ替えても結果が間違っていたりする訳ではないようだ。

% time gtac sorted_tagcount.txt > sorted_tagcount_desc.txt
gtac sorted_tagcount.txt > sorted_tagcount_desc.txt  0.07s user 0.14s system 14% cpu 1.393 total
% time tail -r sorted_tagcount.txt > sorted_tagcount_desc2.txt
tail -r sorted_tagcount.txt > sorted_tagcount_desc2.txt  0.61s user 2.31s system 90% cpu 3.240 total
% diff sorted_tagcount_desc.txt sorted_tagcount_desc2.txt 
% wc -l sorted_tagcount.txt                               
  672870 sorted_tagcount.txt
% ls -lh sorted_tagcount.txt
-rw-r--r--  1 ryu  staff    12M 12 22 18:43 sorted_tagcount.txt