2005/01/20

階層的な連番を振るだけのrubyスクリプト。つまらないものだけど、なんかこういうループって必要なときにすぐに再現できなかったりする。

#!/usr/local/bin/ruby
# seq.rb
# Keiichirou Shikano

# ruby top2title.rb --chap 1 test.txt > result.txt

require "getopts"
getopts(nil,"chap:1")

$i = $OPT_chap.to_i - 1
$j = $k = 0

def headline(line)
head1_pattern = /^■H1■(.*?)$/e
head2_pattern = /^■H2■(.*?)$/e
head3_pattern = /^■H3■(.*?)$/e
head4_pattern = /^■H4■(.*?)$/e
head5_pattern = /^■H5■(.*?)$/e

if line =~ head1_pattern
$i = $i+1
$j = 0
h1_title = "第#{$i}章 #{$1}"
line.sub! head1_pattern, "#{h1_title}"
elsif line =~ head2_pattern
$j = $j+1
$k = 0
h2_title = "#{$i}.#{$j} #{$1}"
line.sub! head2_pattern, "#{h2_title}"
elsif line =~ head3_pattern
$k = $k+1
h3_title = "#{$i}.#{$j}.#{$k} #{$1}"
line.sub! head3_pattern, "#{h3_title}"
elsif line =~ head4_pattern
line.sub! head4_pattern, "■ #{$1}"
elsif line =~ head5_pattern
line.sub! head5_pattern, "▼ #{$1}"
end
end

# main

ARGF.each {|line|
headline(line)

print line + "\n"
}

0 件のコメント: