blog

技術|Linuxのfmtコマンドを使ってテキストを整形する

fmtコマンドは簡単なテキスト整形プログラムです。ここでは、テキストや電子メールの返信の書式設定に使う方法を紹介します。...

Oct 28, 2025 · 3 min. read
シェア

fmtコマンドは簡単なテキスト整形プログラムです。ここでは、テキストや電子メールの返信の書式設定に使う方法を紹介します。

Linux fmtコマンドによるテキストの書式設定

fmtコマンドは単純なテキスト整形プログラムです。単語を集めて段落を埋めるだけで、イタリック体や太字などの他のテキストスタイルは適用しません。すべてプレーンテキストです。fmtコマンドを使えば、テキストを読みやすく調整することができます。まずはこの見慣れたサンプルテキストを見てみましょう。

  1. $ cat trek.txt
  2. Space: the final
  3. frontier. These are the voyages
  4. of the starship Enterprise. Its
  5. continuing mission: to explore
  6. strange new worlds. To
  7. seek out new life and new
  8. civilizations. To boldly go
  9. where no one has gone before!

この例のファイルでは、各行の長さが異なり、奇妙な方法で改行されています。プレーン・テキスト・ファイルに多くの変更を加えると、同じような奇妙な改行に出くわすことがあります。このテキストを再フォーマットするには、fmtコマンドを使って段落の行の長さを統一します:

  1. $ fmt trek.txt
  2. Space: the final frontier. These are the voyages of the starship
  3. Enterprise. Its continuing mission: to explore strange new worlds. To
  4. seek out new life and new civilizations. To boldly go where no one has
  5. gone before!

デフォルトでは、fmtはテキストを列幅75のサイズにフォーマットしますが、-wまたは--widthオプションでこれを変更できます:

  1. $ fmt -w 60 trek.txt
  2. Space: the final frontier. These are the voyages of
  3. the starship Enterprise. Its continuing mission: to
  4. explore strange new worlds. To seek out new life and new
  5. civilizations. To boldly go where no one has gone before!

Linux fmt コマンドによる電子メール応答の書式設定

  1. > I like the idea of the interim development builds.
  1. > I like the idea of the interim development builds. This should be a great way to test new changes that everyone can experiment with.

この問題を解決するために、ターミナルを開き、引用したテキストを新しいファイルにコピー&ペーストしました。そして、-pまたは-prefixオプションを使って、各行の「接頭辞」として使う文字をfmtに指示しました。

  1. $ cat > email.txt
  2. > I like the idea of the interim development builds. This should be a great way to test new changes that everyone can experiment with.
  3. $ fmt -p '>' email.txt
  4. > I like the idea of the interim development builds. This should be a
  5. > great way to test new changes that everyone can experiment with.

fmtコマンドは非常にシンプルなテキスト整形プログラムですが、プレーンテキストで文書を書いたり更新したりする際に役立つ多くの便利なことができます。cや-crown-marginは、箇条書きリストのような段落の最初の2行をインデントするオプションです。また、-t や --tagged-paragraph は、インデントされた段落のように、段落の最初の行のインデントを保持します。uまたは--uniform-spacingオプションは、単語と単語の間に1つのスペース、文と文の間に2つのスペースを使用します。

Read next