タブと空白の変換 expand2007年10月25日 11時29分12秒

何らかの事情で、タブと空白の変換が必要になることが時折ある。実は、この作業はなかなか侮れない。スクリプト言語などで、数分ででっちあげるのは不可能なくらい難しいのだ。

一つのタブを四つなり八つなりの空白に置き換えるだ8けなら、造作も無い。しかし、エディタはタブの前にあるタブ幅に満たない空白は無視する。

例えば、空白、空白、タブ、文字とあったとしよう。タブのスペースは標準的な、8 だとする。この時、エディタで文字が表示されるのは、9 字目の位置だ。空白、空白、タブ、空白などとあると、頭痛がしてくる。

誰が最初に思い付いたのかは、知らないが、expand という結構古いプログラムが unix には入っている。expand がこの頭の痛くなる作業をやってくれるのだ。何年か前に、こんなプログラムがあるのかと知ったときは、こんな変わったことをやるプログラムがあるのかと驚いたものだ。

以下のは、FreeBSD から。


% man expand
NAME
     expand, unexpand -- expand tabs to spaces, and vice versa

SYNOPSIS
     expand [-t tab1,tab2,...,tabn] [file ...]
     unexpand [-a] [-t tab1,tab2,...,tabn] [file ...]

DESCRIPTION
     The expand utility processes the named files or the standard input writ-
     ing the standard output with tabs changed into blanks.  Backspace charac-
     ters are preserved into the output and decrement the column count for tab
     calculations.  The expand utility is useful for pre-processing character
     files (before sorting, looking at specific columns, etc.) that contain
     tabs.