LaTeXのソースからすべての \command を抽出するスクリプト

『数学ガール/フェルマーの最終定理』の校正の都合上、LaTeXのソースからすべての \command を抽出するスクリプトを書きました。

# find_tex_commands.rb
require 'pathname'

commands = Array.new
Pathname.glob("*.tex").each do |file|
  open(file, "r") do |f|
    f.each_line do |line|
      line.scan(/\\[a-zA-Z]+/).each do |c|
        next if commands.include?(c)
        commands << c
      end
    end
  end
end
print commands.sort.join("\n")

実行結果はおおよそ以下のようになります。

> ruby find_tex_commands.rb
\LaTeXe
\Longleftrightarrow
\Longrightarrow
(略)
\subsection
\sum
\tableofcontents
\text
\theta
\times
\title
\to
\today
\ton
\tonsub
\underbrace
\underline
(略)

今回のスクリプト作成時、どうしても一行中に複数個のマッチが存在する場合の正規表現の使い方がわからず、lurker_さんにString#scanを教えていただきました。感謝。
追記:
emeitchさんから、Setのほうがすなおかもと教えていただきました。そうですね、uniquenessの保証を自前でやらなくてもよいから…。

# find_tex_commands.rb
require 'pathname'
require 'set'

commands = Set.new
Pathname.glob("*.tex").each do |file|
  open(file, "r") do |f|
    f.each_line do |line|
      line.scan(/\\[a-zA-Z]+/).each do |c|
        # next if commands.include?(c)
        commands << c
      end
    end
  end
end
print commands.sort.join("\n")