\input texinfo  @c -*-texinfo-*-
@c Do not edit this file!! It is automatically generated from sed-in.texi.
@c
@c -- Stuff that needs adding: ----------------------------------------------
@c (document the `;' command-separator)
@c --------------------------------------------------------------------------
@c
@c %**start of header
@setfilename sed-ja.info
@settitle sed, a stream editor
@c %**end of header

@c @documentlanguage ja

@c @smallbook

@include sed-v.texi

@c Combine indices.
@syncodeindex ky cp
@syncodeindex pg cp
@syncodeindex tp cp

@defcodeindex op
@syncodeindex op fn

@direntry
* sed(ja): (sed-ja).                   Stream EDitor.

@end direntry

@clear PERL

@set SSEDEXT @acronym{GNU} extensions
@set SSED @acronym{GNU} @code{sed}

@copying
This file documents version @value{VERSION} of
@value{SSED}, a stream editor.

@ignore
Published by the Free Software Foundation, @*
59 Temple Place - Suite 330 @*
Boston, MA 02111-1307, USA
@end ignore

Copyright (C) 1998, 1999, 2001, 2002 Free Software Foundation, Inc.

This document is released under the terms of the GNU Free Documentation
License as published by the Free Software Foundation; either version 1.1, or
(at your option) any later version.

You should have received a copy of the GNU Free Documentation License along
with @value{SSED}; see the file @file{COPYING.DOC}.  If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

There are no Cover Texts and no Invariant Sections; this text, along
with its equivalent in the printed manual, constitutes the Title Page.
@end copying

@setchapternewpage off

@titlepage
@title sed, a stream editor
@subtitle version @value{VERSION}, @value{UPDATED}
@author by Ken Pizzini, Paolo Bonzini
@c 翻訳：西尾 太

@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1998, 1999 Free Software Foundation, Inc.

@insertcopying
@end titlepage

@ifnottex

@node Top
@top

@insertcopying
@end ifnottex

@menu
* Introduction::               Introduction
* Invoking sed::               Invocation
* sed Programs::               @code{sed} programs
* Examples::                   Some sample scripts
* Limitations::                Limitations and (non-)limitations of @value{SSED}
* Other Resources::            Other resources for learning about @code{sed}
* Reporting Bugs::             Reporting bugs

* Extended regexps::           @code{egrep}-style regular expressions
@ifset PERL
* Perl regexps::               Perl-style regular expressions
@end ifset

* Concept Index::              A menu with all the topics in this manual.
* Command and Option Index::   A menu with all @code{sed} commands and
                               command-line options.

@detailmenu
@c --- The detailed node listing ---
@c 
--- 詳細なノードリスト ---

@c sed Programs:
@c 
sed プログラム:
* Addresses::                       Selecting lines with @code{sed}
* Regular Expressions::             Overview of regular expression syntax
* Data Spaces::                     Where @code{sed} buffers data
* Common Commands::                 Often used commands
* The "s" Command::                 @code{sed}'s Swiss Army Knife
* Other Commands::                  Less frequently used commands
* Programming Commands::            Commands for @code{sed} gurus
* SSED-specific Commands::          Commands specific of @value{SSED}
* Escapes::                         Specifying special characters

@c Examples:
@c 
例:
* Centering lines::
* Increment a number::
* Rename files to lower case::
* Print bash environment::
* Reverse chars of lines::
* tac::                             Reverse lines of files
* cat -n::                          Numbering lines
* cat -b::                          Numbering non-blank lines
* wc -c::                           Counting chars
* wc -w::                           Counting words
* wc -l::                           Counting lines
* head::                            Printing the first lines
* tail::                            Printing the last lines
* uniq::                            Make duplicate lines unique
* uniq -d::                         Print duplicated lines of input
* uniq -u::                         Remove all duplicated lines
* cat -s::                          Squeezing blank lines

@ifset PERL
@c Perl regexps::                      Perl-style regular expressions
@c 
Perlの正規表現::                    パール形式の正規表現
* Backslash::                       Introduces special sequences
* Caret/dollar/full stop::          Behave specially with regard to new lines
* Square brackets::                 Are a bit different in strange cases
* Options setting::                 Toggle modifiers in the middle of a regexp
* Non-capturing subpatterns::       Are not counted when backreferencing
* Repetition::                      Allows for non-greedy matching
* Backreferences::                  Allows for more than 10 back references
* Assertions::                      Allows for complex look ahead matches
* Non-backtracking subpatterns::    Often gives more performance
* Conditional subpatterns::         Allows if/then/else branches
* Recursive patterns::              For example to match parentheses
* Comments::                        Because things can get complex...
@end ifset

@end detailmenu
@end menu


@node Introduction
@c @chapter Introduction
@chapter はじめに

@cindex Stream editor
@c @code{sed} is a stream editor.
@c A stream editor is used to perform basic text
@c transformations on an input stream
@c (a file or input from a pipeline).
@c While in some ways similar to an editor which
@c permits scripted edits (such as @code{ed}),
@c @code{sed} works by making only one pass over the
@c input(s), and is consequently more efficient.
@c But it is @code{sed}'s ability to filter text in a pipeline
@c which particularly distinguishes it from other types of
@c editors.
@c 
@code{sed}はストリームエディタです．ストリームエディタとは，入力のストリー
ム(ファイルやパイプラインからの入力)で，基本的なテキスト変換を実行するた
めに使用されます．(@code{ed}のように)スクリプトで編集可能なエディタに似
たところもありますが，@code{sed}は入力を一回のみ通過させることで動作し，
そのためより効率的になっています．しかし，他の形式のエディタと特に区別さ
れる点として，パイプラインでテキストにフィルタをかける能力が@code{sed}に
あることがあげられます．

@node Invoking sed
@c @chapter Invocation
@chapter 呼び出し

@c @code{sed} may be invoked with the following command-line options:
@c 
@code{sed}は，以下のコマンドラインオプションを用いて呼び出してもかまいま
せん．

@table @samp
@item @code{-V}
@itemx @code{--version}
@opindex -V
@opindex --version
@cindex Version, printing
@c Print out the version of @code{sed} that is being run and a copyright notice,
@c then exit.
@c 
実行している@code{sed}のバージョンと著作権の注意を出力し終了します．

@item @code{-h}
@itemx @code{--help}
@opindex -h
@opindex --help
@cindex Usage summary, printing
@c Print a usage message briefly summarizing these command-line options
@c and the bug-reporting address,
@c then exit.
@c 
これらのコマンドラインオプションを要約した，短い使用方法のメッセージとバ
グを報告するアドレスを出力し終了します．

@item @code{-n}
@itemx @code{--quiet}
@itemx @code{--silent}
@opindex -n
@opindex --quiet
@opindex --silent
@cindex Disabling autoprint, from command line
@c By default, @code{sed} will print out the pattern space
@c at the end of each cycle through the script.
@c These options disable this automatic printing,
@c and @code{sed} will only produce output when explicitly told to
@c via the @code{p} command.
@c 
デフォルトで@code{sed}は，スクリプトのそれぞれの繰り返しの終了時にパター
ンスペースを出力します．これらのオプションで，この自動的な出力を使用不可
能にし，@code{sed}は@code{p}コマンドで明示的に告げるときだけ出力を生成し
ます．

@item @code{-i}[@var{SUFFIX}]
@itemx @code{--in-place[=@var{SUFFIX}]}
@opindex -i
@opindex --in-place
@cindex In-place editing
@cindex @value{SSEDEXT}, in-place editing
@c This option specifies that files are to be edited in-place.
@c @value{SSED} does this by creating a temporary file and
@c sending output to this file rather than to the standard
@c output@footnote{This applies to commands such as @code{=},
@c @code{a}, @code{c}, @code{i}, @code{l}, @code{p}.  You can
@c still write to the standard output by using the @code{w}
@c @cindex @value{SSEDEXT}, @file{/dev/stdout} file
@c or @code{W} commands together with the @file{/dev/stdout}
@c special file}.

このオプションは，その場でファイルを編集することを指定します．
@value{SSED}は一時的なファイルを作成し，標準入力の代わりにこのファイルに
出力を送ります@footnote{これは，@code{=}，@code{a}，@code{c}，@code{i}，
@code{l}，@code{p}のようなコマンドに適用されます．
@cindex @value{SSEDEXT}, @file{/dev/stdout} file
@file{/dev/stdout}の特殊ファイルを用いて@code{w}や@code{W}コマンドを使用
することで，標準出力にも書き出すことが可能です}．

@c When the end of the file is reached, the temporary file is
@c renamed to the output file's original name.
@c 
ファイルの終りに到達したとき，一時ファイルの名前を出力ファイルの元の名前
に変更します．

@c The extension, if supplied, is used to modify the name of
@c the old file before renaming the temporary file (thereby
@c making a backup copy@footnote{Note that @value{SSED}
@c     creates the backup file whether
@c     or not any output is actually changed.}) following
@c this rule: if the extension doesn't contain a @code{*},
@c then it is appended to the end of the current filename
@c as a suffix; if the extension does contain one or more
@c @code{*} characters, then @emph{each} asterisk is
@c replaced with the current filename.  This allows
@c you to add a prefix to the backup file, instead of (or in
@c addition to) a suffix, or even to place backup copies of
@c the original files into another directory (provided the
@c directory already exists).
@c 
拡張子が提供されている場合，一時ファイル(それによってバックアップのコピー
@footnote{@value{SSED}は，出力ファイルが実際に変更されているかどうかに依
存せずバックアップファイルを作成することに注意してください．}が作成され
ます)の名前を変える前に古いファイルの名前を編集するために，以下の規則を
使用します．拡張子が@code{*}を含まない場合，それはファイル名の接尾子とし
て現在のファイル名の終りに後置されます．拡張子が一つ以上の@code{*}文字を
含む場合，@emph{それぞれの}アスタリスクは現在のファイル名で置換されます．
これで，バックアップファイルに接尾子の代わりに(または接尾子に追加で)接頭
辞を追加することや，オリジナルのファイルのバックアップのコピーを(既存の
ディレクトリを提供することで)他のディレクトリに配置することさえ可能にな
ります．

@c This option implies @code{-s}.
@c 
このオプションは@code{-s}を暗黙に指定します．

@item @code{-l} @var{N}
@itemx @code{--line-length=@var{N}}
@opindex -l
@opindex --line-length
@cindex Line length, setting
@c Specify the default line-wrap length for the 'l' command.
@c A length of 0 (zero) means to never wrap long lines.  If
@c not specified, it is taken to be 70.
@c 
'l'コマンドに対するデフォルトの行を丸める長さを指定します．0 (ゼロ)の長
さは，長い行を決して丸めないことを意味します．指定されていない場合，それ
は70になります．

@item @code{-r}
@itemx @code{--regexp-extended}
@opindex -r
@opindex --regexp-extended
@cindex Extended regular expressions, choosing
@cindex @acronym{GNU} extensions, extended regular expressions
@c Use extended regular expressions rather than basic
@c regular expressions.  Extended regexps are those that
@c @code{egrep} accepts; they can be clearer because they
@c usually have less backslashes, but are a @sc{gnu} extension
@c and hence scripts that use it are not portable.
@c @xref{Extended regexps, , Extended regular expressions}.
@c 
基本正規表現ではなく拡張正規表現を使用します．拡張正規表現とは，
@code{egrep}が受け入れるものです．それらは，バックスラッシュが少ないため
より明確になりますが，それは@sc{gnu}の拡張なので，それを使用しているスク
リプトは移植性が無くなります．@xref{Extended regexps, , Extended regular
expressions}.

@ifset PERL
@item @code{-R}
@itemx @code{--regexp-perl}
@opindex -R
@opindex --regexp-perl
@cindex Perl-style regular expressions, choosing
@cindex @value{SSEDEXT}, Perl-style regular expressions
@c Use Perl-style regular expressions rather than basic
@c regular expressions.  Perl-style regexps are extremely
@c powerful but are a @value{SSED} extension and hence scripts that
@c use it are not portable.  @xref{Perl regexps, ,
@c Perl-style regular expressions}.
@c 
基本的な正規表現ではなく，Perl形式の正規表現を使用します．Perl形式の正規
表現は非常に強力ですが，それは@value{SSED}の拡張なので，それを使用してい
るスクリプトは移植性が無くなります．@xref{Perl regexps, , Perl-style
regular expressions}.
@end ifset

@item @code{-s}
@itemx @code{--separate}
@cindex Working on separate files
@c By default, @code{sed} will consider the files specified on the
@c command line as a single continuous long stream.  This @value{SSED}
@c extension allows the user to consider them separate files:
@c range addresses (such as @code{/abc/,/def/}) are not allowed
@c to span several files, line numbers are relative to the start
@c of each file, @code{$} refers to the last line of each file,
@c and files invoked from the @code{R} commands are rewound at the
@c start of each file.
@c 
デフォルトで，@code{sed}はコマンドラインで指定されているファイルが単一の
長いストリームだと考えます．この@value{SSED}の拡張で，ユーザがそれらを別々
のファイルだと考えることを可能にします．(@code{/abc/,/def/}のような)範囲
指定のアドレスは，複数のファイルを跨ぐことができず，ファイルの行番号はそ
れぞれのファイルの開始位置に相対的なものになり，@code{$}はそれぞれのファ
イルの最後の行を参照し，@code{R}コマンドから呼び出されたファイルはそれぞ
れのファイルの最初に巻き戻されます．

@item @code{-u}
@itemx @code{--unbuffered}
@opindex -u
@opindex --unbuffered
@cindex Unbuffered I/O, choosing
@c Buffer both input and output as minimally as practical.
@c (This is particularly useful if the input is coming from
@c the likes of @code{tail -f}, and you wish to see the transformed
@c output as soon as possible.)
@c 
実用最小限，入力と出力の両方をバッファリングします．(入力が@code{tail
-f}のようなものからのときと，できるだけ速く出力を変換して見たいとき，特
に役に立ちます．)

@item @code{-e} @var{script}
@itemx @code{--expression=@var{script}}
@opindex -e
@opindex --expression
@cindex Script, from command line
@c Add the commands in @var{script} to the set of commands to be
@c run while processing the input.
@c 
@var{script}のコマンドを，入力を処理している間に実行するコマンドの組に追
加します．

@item @code{-f} @var{script-file}
@itemx @code{--file=@var{script-file}}
@opindex -f
@opindex --file
@cindex Script, from a file
@c Add the commands contained in the file @var{script-file}
@c to the set of commands to be run while processing the input.
@c 
ファイル@var{script-file}に含まれているコマンドを，入力を処理している間
に実行するコマンドの組に追加します．

@end table

@c If no @samp{-e}, @samp{-f}, @samp{--expression}, or @samp{--file}
@c options are given on the command-line,
@c then the first non-option argument on the command line is
@c taken to be the @var{script} to be executed.
@c 
@samp{-e}，@samp{-f}，@samp{--expression}，または@samp{--file}オプション
がコマンドラインで全く与えられていない場合，コマンドライン上の最初のオプ
ションではない引数が実行するスクリプトとして渡されます．

@cindex Files to be processed as input
@c If any command-line parameters remain after processing the above,
@c these parameters are interpreted as the names of input files to
@c be processed.
@c 
コマンドラインのパラメータが上記のものを処理した後に残っている場合，これ
らのパラメータは，処理する入力ファイルの名前として解釈されます．
@cindex Standard input, processing as input
@c A file name of @samp{-} refers to the standard input stream.
@c The standard input will be processed if no file names are specified.
@c 
@samp{-}のファイル名は標準入力を参照します．ファイル名が指定されていない
場合，標準入力が処理されます．

@node sed Programs
@c @chapter @code{sed} Programs
@chapter @sc{sed}プログラム

@cindex @code{sed} program structure
@cindex Script structure
@c A @code{sed} program consists of one or more @code{sed} commands,
@c passed in by one or more of the
@c @samp{-e}, @samp{-f}, @samp{--expression}, and @samp{--file}
@c options, or the first non-option argument if zero of these
@c options are used.
@c This document will refer to ``the'' @code{sed} script;
@c this will be understood to mean the in-order catenation
@c of all of the @var{script}s and @var{script-file}s passed in.
@c 
@code{sed}プログラムは，一つ以上の@code{sed}コマンド，一つ以上の
@samp{-e}，@samp{-f}，@samp{--expression}，そして@samp{--file}オプション，
またはこれらのオプションが使用されていない場合は最初のオプションではない
引数で渡されるものから成り立っています．このドキュメントは``その''
@code{sed}スクリプトを記述します．渡される@var{script}と
@var{script-file}を全て連結したものの意味はこれで理解できるでしょう．

@c Each @code{sed} command consists of an optional address or
@c address range, followed by a one-character command name
@c and any additional command-specific code.
@c 
それぞれの@code{sed}コマンドは，オプションのアドレスやアドレスの範囲から
成り立っていて，それには一文字のコマンド名と追加のコマンド特有のコードが
続きます．

@menu
* Addresses::                Selecting lines with @code{sed}
* Regular Expressions::      Overview of regular expression syntax
* Data Spaces::              Where @code{sed} buffers data
* Common Commands::          Often used commands
* The "s" Command::          @code{sed}'s Swiss Army Knife
* Other Commands::           Less frequently used commands
* Programming Commands::     Commands for @code{sed} gurus
* SSED-specific Commands::   Commands specific of @value{SSED}
* Escapes::                  Specifying special characters
@end menu


@node Addresses
@c @section Selecting lines with @code{sed}
@section @code{sed}で行を選択する
@cindex Addresses, in @code{sed} scripts
@cindex Line selection
@cindex Selecting lines to process

@c Addresses in a @code{sed} script can be in any of the following forms:
@c 
@code{sed}スクリプトのアドレスは，以下の形式のどれでも可能です．
@table @samp
@item @var{number}
@cindex Address, numeric
@cindex Line, selecting by number
@c Specifying a line number will match only that line in the input.
@c (Note that @code{sed} counts lines continuously across all input files
@c unless @code{-i} or @code{-s} options are specified.)
@c 
行番号の指定は，入力のその行だけにマッチします．(@code{sed}は，@code{-i} 
や@code{-s}オプションが指定されていない限り，全ての入力行に渡り，連続し
て行を数えることに注意してください．)

@item @var{first}~@var{step}
@cindex @acronym{GNU} extensions, @code{@var{n}~@var{m}} addresses
@c This @sc{gnu} extension matches every @var{step}th line
@c starting with line @var{first}.
@c In particular, lines will be selected when there exists
@c a non-negative @var{n} such that the current line-number equals
@c @var{first} + (@var{n} * @var{step}).
@c Thus, to select the odd-numbered lines,
@c one would use @code{1~2};
@c to pick every third line starting with the second, @code{2~3} would be used;
@c to pick every fifth line starting with the tenth, use @code{10~5};
@c and @code{50~0} is just an obscure way of saying @code{50}.
@c 
この@sc{gnu}の拡張は，行@var{first}で始まり@var{step}番目ごとの行にマッ
チします．特に，負ではない@var{n}が存在するとき，現在の行番号が
@var{first} + (@var{n} * @var{step})になる行が選択されます．このため，偶
数行を選択するため，@code{1~2}を使用することになるでしょう．二行目から始
まり三行ごとに取り上げるため，@code{2~3}を使用することになるでしょう．十
行目から始まり五行ごとに取り上げるため，@code{10~5}を使用することになる
でしょう．そして，@code{50~0}は@code{50}告げる曖昧な方法にすぎません．

@item $
@cindex Address, last line
@cindex Last line, selecting
@cindex Line, selecting last
@c This address matches the last line of the last file of input, or
@c the last line of each file when the @code{-i} or @code{-s} options
@c are specified.
@c 
このアドレスは，入力の最後のファイルの最後の行や，@code{-i}や@code{-s} 
オプションが与えられているときは，それぞれのファイルの最後の行にマッチし
ます．

@item /@var{regexp}/
@cindex Address, as a regular expression
@cindex Line, selecting by regular expression match
@c This will select any line which matches the regular expression @var{regexp}.
@c If @var{regexp} itself includes any @code{/} characters,
@c each must be escaped by a backslash (@code{\}).
@c 
正規表現@var{regexp}にマッチする全ての行を選択します．@var{regexp}自身に
@code{/}文字が含まれる場合，それぞれバックスラッシュ(@code{\})でエスケー
プする必要があります．

@cindex empty regular expression
@cindex @code{POSIXLY_CORRECT} behavior, empty regular expression
@cindex @acronym{GNU} extensions, modifiers and the empty regular expression
@cindex @value{SSEDEXT}, modifiers and the empty regular expression
@c Unless @code{POSIXLY_CORRECT} is set, the empty regular expression
@c @code{//} repeats the last regular expression match (the same holds
@c if the empty regular expression is passed to the @code{s} command).
@c Note that modifiers to regular expressions are evaluated
@c when the regular expression is compiled, thus it is illegal to specify
@c them together with the empty regular expression.
@c If @code{POSIXLY_CORRECT} is set, instead, @code{//} is the null match:
@c this behavior is mandated by @sc{posix}, but it would break too many legacy
@c sed scripts to blithely change @value{SSED}'s default behavior.
@c 
@code{POSIXLY_CORRECT}が設定されていない場合，空の正規表現@code{//}は，
前回の正規表現に繰り返しマッチします(それは，空の正規表現が@code{s}コマ
ンドに渡されても同じです)．正規表現を編集すると，正規表現がコンパイルさ
れるときに評価されるので，空の正規表現とともにそれらを指定することは不正
な処理になることに注意してください．代わりに@code{POSIXLY_CORRECT}が設定
されている場合，@code{//}は何にもマッチしません．この動作は@sc{posix}か
ら依頼されていますが，@value{SSED}のデフォルトの動作を軽率に変更すると，
かなり多くの古いsedスクリプトが駄目になるでしょう．

@item \%@var{regexp}%
@c (The @code{%} may be replaced by any other single character.)
@c 
(@code{%}はその他全ての単一の文字で置換してもかまいません．)

@cindex Slash character, in regular expressions
@c This also matches the regular expression @var{regexp},
@c but allows one to use a different delimiter than @code{/}.
@c This is particularly useful if the @var{regexp} itself contains
@c a lot of @code{/}s, since it avoids the tedious escaping of every @code{/}.
@c If @var{regexp} itself includes any delimiter characters,
@c each must be escaped by a backslash (@code{\}).
@c 
これは正規表現@var{regexp}にもマッチしますが，これで@code{/}以外の分離文
字を使用することが可能になります．@var{regexp}自身が大量の@code{/}を含ん
でいる場合，個々の@code{/}をエスケープするのも退屈なので，それを避けると
き特に役に立ちます．@var{regexp}自身が分離文字を含んでいる場合，それぞれ
をバックスラッシュ(@code{\})でエスケープする必要があります．

@item /@var{regexp}/I
@itemx \%@var{regexp}%I
@cindex @acronym{GNU} extensions, @code{I} modifier
@ifset PERL
@cindex Perl-style regular expressions, case-insensitive
@end ifset
@c The @code{I} modifier to regular-expression matching is a @sc{gnu}
@c extension which causes the @var{regexp} to be matched in
@c a case-insensitive manner.
@c 
正規表現のマッチに対する@code{I}指示語は@sc{gnu}の拡張で，それにより
@var{regexp}は大文字小文字を無視してマッチします．

@item /@var{regexp}/M
@itemx \%@var{regexp}%M
@ifset PERL
@cindex @value{SSEDEXT}, @code{M} modifier
@end ifset
@cindex Perl-style regular expressions, multiline
@c The @code{M} modifier to regular-expression matching is a @value{SSED}
@c extension which causes @code{^} and @code{$} to match respectively
@c (in addition to the normal behavior) the empty string after a new-line,
@c and the empty string before a new-line.  There are special character
@c sequences (@code{\A} and @code{\Z} in Perl mode, @code{\`} and @code{\'}
@c in basic or extended regular expression modes) which always match
@c the beginning or the end of the buffer.  @code{M} stands for
@c @cite{multi-line}.
@c 
正規表現のマッチに対する@code{M}指示語は，@value{SSED}の拡張で，@code{^} 
と@code{$}を(通常の動作に加え)それぞれ改行後の空の文字列と改行前の空の文
字列にマッチさせます．バッファの最初とバッファの最後に常にマッチする特別
な文字の並び(Perlモードの@code{\A}と@code{\Z}，基本または拡張正規表現モー
ドの@code{\`}と@code{\'})があります．@code{M}は@cite{multi-line}を意味し
ます．

@ifset PERL
@item /@var{regexp}/S
@itemx \%@var{regexp}%S
@cindex @value{SSEDEXT}, @code{S} modifier
@cindex Perl-style regular expressions, single line
@c The @code{S} modifier to regular-expression matching is only valid
@c in Perl mode and specifies that the dot character (@code{.}) will
@c match the new-line character too.  @code{S} stands for @cite{single-line}.
@c 
正規表現のマッチに対する@code{S}指示語は，Perlモードでのみ有効で，ドット
文字(@code{.})が改行文字にもマッチするように指定します．@code{S}は
@cite{single-line}を意味します．
@end ifset

@ifset PERL
@item /@var{regexp}/X
@itemx \%@var{regexp}%X
@cindex @value{SSEDEXT}, @code{X} modifier
@cindex Perl-style regular expressions, extended
@c The @code{X} modifier to regular-expression matching is also
@c valid in Perl mode only.  If it is used, whitespace in the
@c pattern (other than in a character class) and
@c characters between a @kbd{#} outside a character class and the
@c next newline character are ignored. An escaping backslash
@c can be used to include a whitespace or @kbd{#} character as part
@c of the pattern.
@c 
正規表現のマッチに対する@code{X}指示語も，Perlモードでのみ有効です．それ
が使用されている場合，パターン内の空白(文字集合以外のもの)と，文字集合の
外側の@kbd{#}と次の改行文字の間の文字を無視します．パターンの一部に空白
と@kbd{#}文字を使用するため，バックスラッシュを使用することが可能です．
@end ifset
@end table

@c If no addresses are given, then all lines are matched;
@c if one address is given, then only lines matching that
@c address are matched.
@c 
アドレスが与えられていない場合，全ての行がマッチします．一つのアドレスが
与えられている場合，マッチする行はアドレスがマッチしたものだけになります．

@cindex Range of lines
@cindex Several lines, selecting
@cindex @acronym{GNU} extensions, @code{0} address
@c An address range can be specified by specifying two addresses
@c separated by a comma (@code{,}).
@c An address range matches lines starting from where the first
@c address matches, and continues until the second address matches
@c (inclusively).
@c If the second address is a @var{regexp}, then checking for the
@c ending match will start with the line @emph{following} the
@c line which matched the first address.  As a @sc{gnu} extension, a
@c line number of @code{0} can be used in an address specification
@c like @code{0,/@var{regexp}/} so that @var{regexp} will be
@c matched in the first input line too.
@c 
アドレスの範囲はカンマ(@code{,})で分けられている二つのアドレスで指定する
ことで指定することが可能です．アドレスの範囲は最初のアドレスにマッチして
いる行から始まり，二番目のアドレス(これは含まれます)にマッチするまで続き
ます．二番目のアドレスが正規表現の場合，マッチの終りの調査は，最初のアド
レスにマッチした行の@emph{次の}行から開始されます．@sc{gnu}の拡張として，
@var{regexp}が最初の入力行にもマッチするように，@code{0}の行番号を
@code{0,/@var{regexp}/}のようなアドレス指定で使用することが可能です．

@c If the second address is a @var{number} less than (or equal to)
@c the line matching the first address,
@c then only the one line is matched.
@c 
二番目のアドレスが@var{number}で最初にマッチした行のアドレスより小さい
(または同じ)場合，一行のみマッチします．

@cindex Special addressing forms
@cindex Range with start address of zero
@cindex Zero, as range start address
@cindex @var{addr1},+N
@cindex @var{addr1},~N
@cindex @acronym{GNU} extensions, special two-address forms
@cindex @acronym{GNU} extensions, 0,@var{addr2} addressing
@cindex @acronym{GNU} extensions, @var{addr1},+@var{N} addressing
@cindex @acronym{GNU} extensions, @var{addr1},~@var{N} addressing
@c @value{SSED} also supports some special 2-address forms:
@c 
@value{SSED}も特殊な二つのアドレス形式をサポートしています．
@table @samp
@item 0,@var{addr2}
@c Start out in "matched first address" state,
@c until @var{addr2} is found.
@c This is similar to 1,@var{addr2},
@c except that if @var{addr2} matches the very first line of input
@c the 0,@var{addr2} form will be at the end of its range,
@c whereas the 1,@var{addr2} form will still be at the beginning of its range.
@c 
@var{addr2}が見つかるまで，"最初のアドレスにマッチしている"状態で開始し
ます．これは1,@var{addr2}に似ていますが，@var{addr2}が入力行の最初にマッ
チした場合，0,@var{addr2}の形式はその範囲の最後になりますが，
1,@var{addr2}の形式はその範囲の最初のままです．
@item @var{addr1},+@var{N}
@c Will match @var{addr1} and the @var{N} lines following @var{addr1}.
@c 
@var{addr1}と@var{addr1}に続く@var{N}行にマッチします．
@item @var{addr1},~@var{N}
@c Will match @var{addr1} and the lines following @var{addr1}
@c until the next line whose input line number is a multiple of @var{N}.
@c 
@var{addr1}と，入力の行番号が@var{N}の倍数になるまでの@var{addr1}に続く
行にマッチします．
@end table

@cindex Excluding lines
@cindex Selecting non-matching lines
@c Appending the @code{!} character to the end of an address
@c specification will negate the sense of the match.
@c That is, if the @code{!} character follows an address range,
@c then only lines which do @emph{not} match the address range
@c will be selected.
@c This also works for singleton addresses,
@c and, perhaps perversely, for the null address.
@c 
アドレス指定の終りに@code{!}文字を後置するとマッチの意味が否定されます．
すなわち，@code{!}がアドレスの範囲に続いている場合，選択されたアドレスの
範囲にマッチ@emph{しない}行だけが選択されます．これは一つのアドレスに対
しても動作し，おそらくひねくれているだけでしょうが，何もないアドレスに対
しても動作します．

@node Regular Expressions
@c @section Overview of regular expression syntax
@section 正規表現の構文の概要

@c To know how to use @code{sed}, people should understand regular
@c expressions (@dfn{regexp} for short).  A regular expression
@c is a pattern that is matched against a
@c subject string from left to right. Most characters stand for
@c themselves in a pattern, and match the corresponding characters
@c in the subject. As a trivial example, the pattern
@c 
@code{sed}の使用方法を知るため，正規表現(短くすると@dfn{regexp})を理解す
べきです．正規表現とは，右から左へならぶ対象文字列に対してマッチするパター
ンです．パターン内のほとんどの文字はその文字自身を意味し，対象内の対応す
る文字にマッチします．ちょっとした例として以下のパターンを考えます．

@example
     The quick brown fox
@end example

@noindent
@c matches a portion of a subject string that is identical to
@c itself.  The power of regular expressions comes from the
@c ability to include alternatives and repetitions in the pattern.
@c These are encoded in the pattern by the use of metacharacters,
@c which do not stand for themselves but instead
@c are interpreted in some special way.  Here is a brief description
@c of regular expression syntax as used in @code{sed}.
@c 
それは，それと全く同一なサブジェクトの文字列の一部にマッチします．正規表
現のパワーは，パターン内に代入と繰り返しを含めるという能力にあります．そ
れらはメタ文字を使用してパターン内にエンコードされ，その文字自身を意味せ
ず，特殊な方法で解釈されます．@code{sed}で使用される正規表現の構文の短い
記述は以下のようになります．

@table @code
@item @var{char}
@c A single char, if not special, is matched against text.
@c 
単一文字で，特殊なものでない場合はテキストにマッチします．

@item *
@c Matches a sequence of zero or more repetitions of previous char,
@c grouped regexp (see below), or class.
@c 
直前の文字，まとまった正規表現(以下を参照)，またはクラスの，ゼロ回以上の
繰り返しにマッチします．

@item \+
@cindex @acronym{GNU} extensions, to basic regular expressions
@c As *, but matches one or more.  It is a @sc{gnu} extension.
@c 
*に似ていますが，一つ以上にマッチします．それは@sc{gnu}の拡張です．

@item \?
@cindex @acronym{GNU} extensions, to basic regular expressions
@c As *, but only matches zero or one.  It is a @sc{gnu} extension.
@c 
*に似ていますが，ゼロまたは一つだけにマッチします．れは@sc{gnu}の拡張で
す．

@item \@{@var{i}\@}
@c As *, but matches exactly @var{i} sequences (@var{i} is a
@c number; for portability, keep it between 0 and 255)
@c 
*に似ていますが，正確に@var{i}個連続したものにマッチします(@var{i}は数字
です．移植性のために0から255の間にしてください)．

@item \@{@var{i},@var{j}\@}
@c Matches between @var{i} and @var{j}, inclusive, sequences.
@c 
@var{i}個以上と@var{j}個以下の間の連続にマッチします．

@item \@{@var{i},\@}
@c Matches more than or equal to @var{i} sequences.
@c 
@var{i}個以上の連続にマッチします．

@item \(@var{regexp}\)
@c Groups the inner @var{regexp} as a whole, this is used to: 
@c 
全体として@var{regexp}の内部グループにします．以下のように使用されます．

@itemize @bullet
@item
@c apply postfix operators, like @code{\(abcd\)*}:
@c this will search for zero or more whole sequences 
@c of @samp{abcd}, while @code{abcd*} would search
@c for @samp{abc} followed by zero or more occurrences
@c of @samp{d}
@c 
@code{\(abcd\)*}のような，後置されるオペレータを適用します．これは，ゼロ
以上の@samp{abcd}全体の連続を検索しますが，@code{abcd*}は@samp{abc}にゼ
ロ以上の@samp{d}が続くものを検索します．

@item
@c use back references (see below)
@c 
後方参照を使用します(以下を参照してください)．
@end itemize

@item .
@c Matches any character 
@c 
あらゆる文字にマッチします．

@item ^
@c Match the null string at beginning of line, i.e. what
@c what appears after the caret must appear at the 
@c beginning of line. @code{^#include} will match only 
@c lines where "#include" is the first thing on line---if
@c there are one or two spaces before, the match fails.
@c 
行の最初のヌル文字にマッチし，すなわちキャレットの後にあるものは行の最初
にある必要があります．@code{^#include}は，"#include"が行の最初にあるとこ
ろだけにマッチします --- その前に一つか二つのスペースがある場合，マッチ
は失敗します．

@item $
@c It is the same as @code{^}, but refers to end of line
@c 
@code{^}と同じですが，行の終りを参照します．

@item [@var{list}]
@itemx [^@var{list}]
@c Matches any single char in @var{list}: for example,
@c @samp{[aeiou]} matches all vowels.  A list may include
@c sequences like @samp{@var{char1}-@var{char2}}, which
@c matches any character between (inclusive) @var{char1}
@c and @var{char2}.
@c 
@var{list}内の単一文字にマッチします．例えば，@samp{[aeiou]}はすべての母
音にマッチします．リストには@samp{@var{char1}-@var{char2}}のような並びを
含めてもかまわず，それは，@var{char1}と@var{char2}の間(それぞれ含まれま
す)のあらゆる文字にマッチします．

@c The caret reverses the meaning of the regexp, so that
@c it matches any single char NOT in list.  To include
@c @samp{]} in the list, make it the first character (after
@c the caret if needed), to include @samp{-} in the list,
@c make it the first or last; to include @samp{^} put
@c it after the first character.
@c 
キャレットは正規表現の意味を反転し，リスト以外の単一文字にマッチします．
リストに@samp{]}を含めるため，それを(必要なキャレットの後の)最初の文字に
し，@samp{-}をリストに含めるため，それを最初または最後にしてください．
@samp{^}を含めるため，最初の文字より後に書いてください．

@item @var{regexp1}\|@var{regexp2}
@cindex @acronym{GNU} extensions, to basic regular expressions
@c Matches either @var{regexp1} or @var{regexp2}.  Use
@c parentheses to use complex alternative regular expressions.
@c The matching process tries each alternative in turn, from
@c left to right, and the first one that succeeds is used.
@c It is a @sc{gnu} extension.
@c 
@var{regexp1}または@var{regexp2}にマッチします．複雑な代替正規表現を使用
するためカッコを使用してください．マッチの処理は，それぞれの代替物を左か
ら右へ順番に試し，最初に成功したものが使用されます．それは@sc{gnu}の拡張
です．

@item \@var{digit}
@c Matches the @var{digit}-th @code{\(\)} reference in the
@c regular expression.
@c 
正規表現の@var{digit}番目の@code{\(\)}で参照しているものにマッチします．

@item \@var{char}
@c Matches character @var{char}; this is to be used to match
@c special chars, referred above.  Note that the only C-like
@c backslash sequence that you can portably assume to be
@c interpreted is @code{\n} for a new-line; in particular
@c @code{\t} matches a @samp{t} under most implementations
@c of @code{sed}, rather than a tabulation character.
@c 
メタ文字@var{char}にマッチします．これは上記で言及されている特殊文字にマッ
チさせるために使用されます．移植性があると仮定されるCのようなバックスラッ
シュシーケンスは，改行に対する@code{\n}だけだということに注意してくださ
い．特に@code{\t}は，ほとんどの@code{sed}実装でタブ文字ではなく@samp{t}
にマッチします．

@end table

@cindex Greedy regular expression matching
@c Note that the regular expression matcher is greedy, i.e. if
@c two or more matches are detected, it selects the longest, if
@c there are two or more selected with the same size, it
@c selects the first in text.
@c 
正規表現のマッチは欲張り，つまり二つ以上のマッチが検出された場合は最も長
いものを選択し，二つ以上同じサイズのものを選択した場合はテキストの最初の
ものを選択することに注意してください．

@noindent
@c Examples:
@c 
例です．
@table @samp
@item abcdef
@c Matches @samp{abcdef}
@c 
@samp{abcdef}にマッチします．

@item a*b
@c Matches zero or more @samp{a}s followed by a single
@c @samp{b}.  For example, @samp{b} or @samp{aaaaab}. 
@c 
ゼロ個以上の@samp{a}に単一の@samp{b}が続くものにマッチします．例えば，
@samp{b}や@samp{aaaaab}です．

@item a\?b
@c Matches @samp{b} or @samp{ab}
@c 
@samp{b}や@samp{ab}にマッチします．

@item a\+b\+
@c Matches one or more @samp{a}s followed by one or more
@c @samp{b}s: @samp{ab} is the shorter possible match, but
@c other examples are @samp{aaaab} or @samp{abbbbb} or
@c @samp{aaaaaabbbbbbb}.
@c 
一つ以上の@samp{a}に一つ以上の@samp{b}が続くものにマッチします．
@samp{ab}はマッチの可能性がある最も短いものですが，それ以外の例として，
@samp{aaaab}や@samp{abbbbb}や@samp{aaaaaabbbbbbb}があります．

@item .*
@itemx .\+
@c These two will both match all the characters on a line;
@c however, the first will match every line (including empty
@c ones), while the second will only match lines containing
@c at least one char.
@c 
これらの二つは両方とも，行のすべての文字にマッチします．しかし，最初のも
のはすべての行(空のものも含む)にマッチしますが，二番目のものは少なくとも
一文字含まれている行のみにマッチします．

@item ^main.*(.*)
@c This will search for a line containing "main" as the first
@c thing on the line, followed by an opening and closing
@c parenthesis.  The @samp{n}, @samp{(} and @samp{)} need not
@c be adjacent
@c 
これは，行の最初が"main"で，開カッコと閉カッコが続く行を探します．隣接す
る@samp{n}，@samp{(}，そして@samp{)}は不要です．

@item ^#
@c This will match lines beginning with a hash (or sharp)
@c character.
@c 
これは，ハッシュ(またはシャープ)文字で始まる行にマッチします．

@item \\$
@c This will match lines ending with a single backslash.  The
@c regexp contains two backslashes for escaping.
@c 
これは単一のバックスラッシュで終る行にマッチします．その正規表現は，エス
ケープのために二つのバックスラッシュを含みます．

@item \$
@c Instead, this will match lines containing a single dollar,
@c because it is escaped.
@c 
代わりに，これは単一のドル記号にマッチし，それはエスケープされているため
です．

@item [a-zA-Z_]
@c This will match any letters or digits
@c 
これはあらゆる文字にマッチします．

@item [^ @kbd{tab}]\+
@c This will match one or more sequences
@c of any char that isn't a space or tab.
@c Usually this means a word
@c 
これは，スペースとタブ以外のあらゆる文字が一つ以上連続しているものにマッ
チします．通常，これは単語を意味します．

@item ^\(.*\)\n\1$
@c This will match two equal lines without a trailing new-line
@c 
これは，最後の改行以外の二つの同じ行にマッチします．

@item A.\@{9\@}$
@c This will match an "A" that is exactly the last tenth
@c character on line
@c 
これは，行の最後の十文字が正確に"A"であるものにマッチします．

@item ^.\@{,15\@}A
@c Match the last "A" on the first 16 chars of the line
@c 
行の最初の16文字の終りの"A"にマッチします．

@end table



@node Data Spaces
@c @section Where @code{sed} buffers data
@section @code{sed}がデータをバッファリングする場所

@cindex Buffer spaces, pattern and hold
@cindex Spaces, pattern and hold
@cindex Pattern space, definition
@cindex Hold space, definition
@c @code{sed} maintains two data buffers: the active @emph{pattern} space,
@c and the auxiliary @emph{hold} space.
@c In ``normal'' operation, @code{sed} reads in one line from the
@c input stream and places it in the pattern space.
@c This pattern space is where text manipulations occur.
@c The hold space is initially empty, but there are commands
@c for moving data between the pattern and hold spaces.
@c 
@code{sed}は二つのデータバッファを管理します，アクティブな@emph{パターン} 
スペースと，補助的な@emph{ホールド}スペースです．``通常の''処理では，
@code{sed}は入力ストリームから一行読み込み，それをパターンスペースに配置
します．このパターンスペースとは，テキストの操作を行なう場所です．ホール
ドスペースは最初は空ですが，パターンスペースからホールドスペース間でデー
タを移動するコマンドがあります．
@c XXX FIXME: explain why this is useful/interesting to know.


@node Common Commands
@c @section Often used commands
@section よく使用されるコマンド

@c If you use @code{sed} at all, you will quite likely want to know
@c these commands.
@c 
本当に@code{sed}を使用するのなら，きっとこれらのコマンドを知りたいと思う
でしょう．

@table @samp
@item #
@c [No addresses allowed.]
@c 
[アドレスは利用不可能です．]

@findex # (comments)
@cindex Comments, in scripts
@c The @code{#} character begins a comment;
@c the comment continues until the next newline.
@c 
@code{#}``コマンド''はコメントを開始します．コメントは次の改行まで続きま
す．

@cindex Portability, comments
@c If you are concerned about portability, be aware that
@c some implementations of @code{sed} (which are not @sc{posix.2}
@c conformant) may only support a single one-line comment,
@c and then only when the very first character of the script is a @code{#}.
@c 
移植性を心配している場合，@code{sed}(@sc{posix.2}に準拠していないもの)の
実装によっては，単一の一行のコメントのみサポートしていて，スクリプトの最
初の文字が@code{#}のときだけサポートしている可能性があることを覚えておい
てください．

@findex -n, forcing from within a script
@cindex Caveat --- #n on first line
@c Warning: if the first two characters of the @code{sed} script
@c are @code{#n}, then the @samp{-n} (no-autoprint) option is forced.
@c If you want to put a comment in the first line of your script
@c and that comment begins with the letter `n'
@c and you do not want this behavior,
@c then be sure to either use a capital `N',
@c or place at least one space before the `n'.
@c 
警告：@code{sed}スクリプトの最初の二文字が@code{#n}の場合，@samp{-n}(自
動的に出力しない)オプションが強制的に使用されます．スクリプトの最初の行
にコメントを書き，そしてコメントを文字`n'で開始したい場合で，このように
動作して欲しくない場合は，大文字の`N'を使用するか，`n'の前に少なくとも一
つのスペースを書いてください．

@item q [@var{exit-code}]
@c [At most one address allowed.]
@c 
[最大一つのアドレスが可能です．]

@findex q (quit) command
@cindex @value{SSEDEXT}, returning an exit code
@cindex Quitting
@c Exit @code{sed} without processing any more commands or input.
@c Note that the current pattern space is printed if auto-print is
@c not disabled with the @code{-n} switch.  The ability to return
@c an exit code from the @code{sed} script is a @value{SSED} extension.
@c 
それ以上のコマンドも入力も処理せず@code{sed}を終了します．自動的な出力が
@code{-n}スイッチで利用不可能になっていない場合，現在のパターンスペース
が出力されることに注意してください．@code{sed}スクリプトがからの終了コー
ドを返す能力は，@value{SSED}の拡張です．

@item d
@findex d (delete) command
@cindex Text, deleting
@c Delete the pattern space;
@c immediately start next cycle.
@c 
パターンスペースを削除します．すぐに次のサイクルを開始します．

@item p
@findex p (print) command
@cindex Text, printing
@c Print out the pattern space (to the standard output).
@c This command is usually only used in conjunction with the @samp{-n}
@c command-line option.
@c 
パターンスペースを(標準出力に)出力します．通常このコマンドは，@code{-n} 
コマンドラインオプションと組み合わせて使用します．

@c Note: some implementations of @code{sed}, such as this one, will
@c double-print lines when auto-print is not disabled and the @code{p}
@c command is given.
@c Other implementations will only print the line once.
@c Both ways conform with the @sc{posix.2} standard, and so neither
@c way can be considered to be in error.
@c 
注意：このような@code{sed}の実装では，自動的な出力が利用不可能ではなく
@code{p}が与えられているとき，出力行が二重になるものもあります．それ以外
の実装では，行は一回だけ出力されます．両方とも@sc{posix.2}の標準に準拠し
ていて，どちらかをエラーと考えることはできません．

@cindex Non-bugs, @code{p} command and @samp{-n} flag
@cindex Portability, @code{p} command and @samp{-n} flag
@c Portable @code{sed} scripts should thus avoid relying on either behavior;
@c either use the @samp{-n} option and explicitly print what you want,
@c or avoid use of the @code{p} command (and also the @code{p} flag to the
@c @code{s} command).
@c 
このため，移植性の高い@code{sed}スクリプトでは，どちらかの動作に依存する
ことは避けるべきです．@samp{-n}を使用して出力したいものを明示的にするか，
@code{p}コマンド(と@code{s}コマンドの@code{p}フラグ)の使用を避けてくださ
い．

@item n
@findex n (next-line) command
@cindex Next input line, replace pattern space with
@cindex Read next input line
@c If auto-print is not disabled, print the pattern space,
@c then, regardless, replace the pattern space with the next line of input.
@c If there is no more input then @code{sed} exits without processing
@c any more commands.
@c 
自動的な出力が利用不可能ではない場合，パターンスペースを出力し，何も考え
ず，パターンスペースを入力の次の行で置換します．それ以上入力がない場合，
@code{sed}はそれ以上のコマンドを処理せずに終了します．

@item @{ @var{commands} @}
@findex @{@} command grouping
@cindex Grouping commands
@cindex Command groups
@c A group of commands may be enclosed between
@c @code{@{} and @code{@}} characters.
@c This is particularly useful when you want a group of commands
@c to be triggered by a single address (or address-range) match.
@c 
コマンドのグループは，@code{@{}文字と@code{@}}文字で囲んでもかまいません．
コマンドのグループを，単一のアドレス(またはアドレスの範囲)にマッチしたこ
とで開始したいとき，これは特に役に立ちます．

@end table

@node The "s" Command
@c @section The @code{s} Command
@section @code{s}コマンド

@c The syntax of the @code{s} (as in substitute) command is
@c s/@var{regexp}/@var{replacement}/@var{flags}.  The @code{/}
@c characters may be uniformly replaced by any other single
@c character within any given @code{s} command.  The @code{/}
@c character (or whatever other character is used in its stead)
@c can appear in the @var{regexp} or @var{replacement}
@c only if it is preceded by a @code{\} character.
@c 
(置換での)@code{s}コマンドの構文は，
s/@var{regexp}/@var{replacement}/@var{flags}です．@code{/}文字は，他の単
一文字を@code{s}コマンドで与えることで一様に置換してもかまいません．
@code{/}文字(または，それの代わりの使用されているその他の文字)は，
@code{\}文字を前置した場合だけ@var{regexp}や@var{replacement}に書くこと
が可能です．

@c The @code{s} command is probably the most important in @code{sed}
@c and has a lot of different options.  Its basic concept is simple:
@c the @code{s} command attempts to match the pattern
@c space against the supplied @var{regexp}; if the match is
@c successful, then that portion of the pattern
@c space which was matched is replaced with @var{replacement}.
@c 
@code{s}コマンドは，おそらく@code{sed}で最も重要で，様々なオプションが多
くあります．基本的な概念は単純です．@code{s}コマンドは，提供されている
@var{regexp}に対しパターンスペースのマッチを試みます．マッチが成功する場
合．マッチしたパターンスペースの位置が@var{replacement}で置換されます．

@cindex Backreferences, in regular expressions
@cindex Parenthesized substrings
@c The @var{replacement} can contain @code{\@var{n}} (@var{n} being
@c a number from 1 to 9, inclusive) references, which refer to
@c the portion of the match which is contained between the @var{n}th
@c @code{\(} and its matching @code{\)}.
@c Also, the @var{replacement} can contain unescaped @code{&}
@c characters which will reference the whole matched portion
@c of the pattern space.
@c 
@var{replacement}に@code{\@var{n}}(@var{n}は1から9までの数字で，1と9も含
まれます)での参照を含めることが可能で，それは@var{n}番目の@code{\(}とそ
のマッチと@code{\)}に含まれているマッチの位置を参照します．また，
@var{replacement}に，パターンスペースのマッチ位置全体を参照する，エスケー
プされていない@code{&}文字を含めることも可能です．
@cindex @value{SSEDEXT}, case modifiers in `s' commands
@c Finally (this is a @value{SSED} extension) you can include a
@c special sequence made of a backslash and one of the letters
@c @code{LlUuE}.  The meaning is, respectively: turn the replacement
@c to lowercase until a @code{\U} or @code{\E} is found, turn the
@c next character to lowercase, turn the replacement to uppercase
@c until a @code{\L} or @code{\E} is found, turn the next character
@c to uppercase, and stop case conversion started by @code{\L} or
@c @code{\U}.
@c To include a literal @code{\}, @code{&}, or newline in the final
@c replacement, be sure to precede the desired @code{\}, @code{&},
@c or newline in the @var{replacement} with a @code{\}.
@c 
最終的に(これは@value{SSED}の拡張です)，特別なバックスラッシュの並びや文
字@code{LlUuE}の一つを含めることが可能です．それぞれの意味は以下のとおり
です．@code{\U}や@code{\E}が見つかるまで小文字に置換します．次の文字を小
文字に置換します．@code{\L}や@code{\E}が見つかるまで大文字に置換します．
次の文字を大文字に置換します．そして，@code{\L}や@code{\U}で開始した大文
字小文字の変換を停止します．@code{\}，@code{&}，または改行そのものを最終
的な置換物に含めるため，@var{replacement}内の@code{\}，@code{&}，または
改行に必要な@code{\}を確実に前置してください．

@findex s command, option flags
@cindex Substitution of text, options
@c The @code{s} command can be followed with zero or more of the
@c following @var{flags}:
@c 
@code{s}コマンドにはゼロ以上の以下の@var{flags}を続けることが可能です．

@table @samp
@item g
@cindex Global substitution
@cindex Replacing all text matching regexp in a line
@c Apply the replacement to @emph{all} matches to the @var{regexp},
@c not just the first.
@c 
最初のものだけでなく@emph{すべての}@var{regexp}へのマッチを置換します．

@item @var{number}
@cindex Replacing only @var{n}th match of regexp in a line
@c Only replace the @var{number}th match of the @var{regexp}.
@c 
@var{regexp}の@var{number}番目のマッチのみ置換します．

@cindex @acronym{GNU} extensions, @code{g} and @var{number} modifier interaction in @code{s} command
@cindex Mixing @code{g} and @var{number} modifiers in the @code{s} command
@c Note: the @sc{posix.2} standard does not specify what should happen
@c when you mix the @code{g} and @var{number} modifiers,
@c and currently there is no widely agreed upon meaning
@c across @code{sed} implementations.
@c For @value{SSED}, the interaction is defined to be:
@c ignore matches before the @var{number}th,
@c and then match and replace all matches from
@c the @var{number}th on.
@c 
注意：@sc{posix.2}の標準は，@code{g}と@var{number}指示語を混ぜたときに何
が起こるかを指定しておらず，現在は@code{sed}の実装上で幅広い同意はありま
せん．@value{SSED}では，相互作用は以下のように定義しています．
@var{number}番目のマッチを無視し，@var{number}番目からマッチし，すべての
マッチを置換します．

@item p
@cindex Text, printing after substitution
@c If the substitution was made, then print the new pattern space.
@c 
置換が行なわれた場合，新しいパターンスペースを出力します．

@c Note: when both the @code{p} and @code{e} options are specified,
@c the relative ordering of the two produces very different results.
@c In general, @code{ep} (evaluate then print) will be what you want,
@c but operating the other way round can be useful for debugging.
@c For this reason, the current versions of @value{SSED} interprets
@c specially the presence of @code{p} options both before and after
@c @code{e}, printing pattern space before and after evaluation,
@c while in general flags for the @code{s} command show their
@c effect just once.  This behavior, although documented, might
@c change in future versions.
@c 
注意：@code{p}と@code{e}オプションの両方が指定されているとき，二つの順序
に関連して，全く違った結果を生成します．一般的に@code{ep}(評価して出力) 
では期待したものになるでしょうが，もう一方の順番はデバッグで役に立つもの
になります．この理由は，現在のバージョンの@value{SSED}が，@code{e}前後の
@code{p}オプションの存在を特別なものとして解釈しますが，@code{s}コマンド
に対する一般的なフラグはその効果を一度だけ表示するためです．この動作は，
ドキュメントには書かれていますが，将来のバージョンでは変更するかもしれま
せん．

@item w @var{file-name}
@cindex Text, writing to a file after substitution
@cindex @value{SSEDEXT}, @file{/dev/stdout} file
@cindex @value{SSEDEXT}, @file{/dev/stderr} file
@c If the substitution was made, then write out the result to the named file.
@c As a @value{SSED} extension, two special values of @var{file-name} are
@c supported: @file{/dev/stderr}, which writes the result to the standard
@c error, and @file{/dev/stdout}, which writes to the standard
@c output.@footnote{This is equivalent to @code{p} unless the @code{-i}
@c switch is being used.}
@c 
置換が行なわれた場合，結果を指名されたファイルに書き出します．
@value{SSED}の拡張として，@var{file-name}の特殊な値をサポートします．結
果を標準エラー出力に書き出す@file{/dev/stderr}，そして標準出力に書き出す
@file{/dev/stdout}です．@footnote{これは，@code{-i}スイッチが使用されて
いない限り，@code{p}と等価です．}

@item e
@cindex Evaluate Bourne-shell commands, after substitution
@cindex Subprocesses
@cindex @value{SSEDEXT}, evaluating Bourne-shell commands
@cindex @value{SSEDEXT}, subprocesses
@c This command allows one to pipe input from a shell command
@c into pattern space.  If a substitution was made, the command
@c that is found in pattern space is executed and pattern space
@c is replaced with its output.  A trailing new-line is suppressed;
@c results are undefined if the command to be executed contains
@c a @code{nul} character.  This is a @value{SSED} extension.
@c 
このコマンドで，シェルコマンドからの入力をパターンスペースへのパイプで渡
すことが可能になります．代入が行なわれた場合，パターンスペースで見つかっ
たコマンドが実行され，パターンスペースはその出力で置換されます．後置され
る改行は抑制されます．実行されたコマンドに@code{nul}文字が含まれる場合，
結果は定義されていません．これは@value{SSED}の拡張です．

@item I
@itemx i
@cindex @acronym{GNU} extensions, @code{I} modifier
@cindex Case-insensitive matching
@ifset PERL
@cindex Perl-style regular expressions, case-insensitive
@end ifset
@c The @code{I} modifier to regular-expression matching is a @sc{gnu}
@c extension which makes @code{sed} match @var{regexp} in a
@c case-insensitive manner.
@c 
正規表現にマッチさせる@code{I}修飾子は@sc{gnu}の拡張で，大文字小文字を無
視する方法で，@code{sed}に@var{regexp}にマッチさせます．

@item M
@itemx m
@cindex @value{SSEDEXT}, @code{M} modifier
@ifset PERL
@cindex Perl-style regular expressions, multiline
@end ifset
@c The @code{M} modifier to regular-expression matching is a @value{SSED}
@c extension which causes @code{^} and @code{$} to match respectively
@c (in addition to the normal behavior) the empty string after a new-line,
@c and the empty string before a new-line.  There are special character
@c sequences (@code{\A} and @code{\Z} in Perl mode, @code{\`} and @code{\'}
@c in basic or extended regular expression modes) which always match
@c the beginning or the end of the buffer.  @code{M} stands for
@c @cite{multi-line}.
@c 
正規表現のマッチに対する@code{M}指示語は，@value{SSED}の拡張で，@code{^} 
と@code{$}を(通常の動作に加え)，それぞれ改行後の空の文字列と改行前の空の
文字列にマッチさせます．バッファの最初とバッファの最後に常にマッチする特
別な文字の並び(Perlモードの@code{\A}と@code{\Z}，基本または拡張正規表現
モードの@code{\`}と@code{\'})があります．@code{M}は@cite{multi-line}を意
味します．

@ifset PERL
@item S
@itemx s
@cindex @value{SSEDEXT}, @code{S} modifier
@cindex Perl-style regular expressions, single line
@c The @code{S} modifier to regular-expression matching is only valid
@c in Perl mode and specifies that the dot character (@code{.}) will
@c match the new-line character too.  @code{S} stands for @cite{single-line}.
@c 
正規表現のマッチに対する@code{S}指示語は，Perlモードでのみ有効で，ドット
文字(@code{.})が改行文字にもマッチするように指定します．@code{S}は
@cite{single-line}を意味します．
@end ifset

@ifset PERL
@item X
@itemx x
@cindex @value{SSEDEXT}, @code{X} modifier
@cindex Perl-style regular expressions, extended
@c The @code{X} modifier to regular-expression matching is also
@c valid in Perl mode only.  If it is used, whitespace in the
@c pattern (other than in a character class) and
@c characters between a @kbd{#} outside a character class and the
@c next newline character are ignored. An escaping backslash
@c can be used to include a whitespace or @kbd{#} character as part
@c of the pattern.
@c 
正規表現のマッチに対する@code{X}指示語も，Perlモードでのみ有効です．それ
が使用されている場合，パターン内の空白(文字集合以外のもの)と，文字集合の
外側の@kbd{#}と次の改行文字の間の文字を無視します．パターンの一部に空白
と@kbd{#}文字を使用するため，バックスラッシュを使用することが可能です．
@end ifset
@end table


@node Other Commands
@c @section Less frequently used commands
@section あまり使用されないコマンド

@c Though perhaps less frequently used than those in the previous
@c section, some very small yet useful @code{sed} scripts can be built with
@c these commands.
@c 
前のセクションのものより使用されることはおそらく少ないでしょうが，非常に
わずかな有用な@sc{sed}スクリプトには，以下のコマンドを組み込むことも可能
です．

@table @samp
@item v
@findex v (version) command
@cindex @value{SSEDEXT}, checking for their presence
@cindex Requiring @value{SSED}
@c This command does nothing, but will make @code{sed} fail if
@c @value{SSED} extensions are not supported, simply because other
@c implementations of @code{sed} do not implement it.
@c 
このコマンドは何もしませんが，@value{SSED}の拡張がサポートされていない場
合は@code{sed}は異常終了し，それはその他の@code{sed}の実装ではそれを実装
していないためです．

@item Q [@var{exit-code}]
@findex Q (silent Quit) command
@cindex @value{SSEDEXT}, quitting silently
@cindex @value{SSEDEXT}, returning an exit code
@cindex Quitting
@c This command is the same as @code{q}, but will not print the
@c contents of pattern space.  Like @code{q}, it provides the
@c ability to return an exit code to the caller.
@c 
このコマンドは@code{q}と同じですが，パターンスペースの内容を出力しません．
@code{q}に似ていて，呼び出し側に終了コードを返す能力を提供しています．

@c This command can be useful because the only alternative ways
@c to accomplish this apparently trivial function are to use
@c the @code{-n} option (which can unnecessarily complicate
@c your script) or resorting to the following snippet, which
@c wastes time by reading the whole file without any visible effect:
@c 
この一見些細な機能を達成する唯一の別の方法は，@code{-n}オプションを使用
する方法(スクリプトが不必要に複雑になります)や，見た目に影響しないように
ファイル全体を読み込むことで時間が無駄になるような以下の断片を利用する方
法なので，このコマンドは役に立ちます．

@example
:eat
$d       # @r{Quit silently on the last line}
N        # @r{Read another line, silently}
g        # @r{Overwrite pattern space each time to save memory}
b eat
@end example

@item y/@var{source-chars}/@var{dest-chars}/
@c (The @code{/} characters may be uniformly replaced by
@c any other single character within any given @code{y} command.)
@c 
(@code{/}文字は，@code{y}コマンドで与えられるその他の単一文字で一律に置
換してもかまいません．)

@findex y (transliterate) command
@cindex Transliteration
@c Transliterate any characters in the pattern space which match
@c any of the @var{source-chars} with the corresponding character
@c in @var{dest-chars}.
@c 
@var{source-chars}にマッチしたパターンスペースのすべての文字を，対応する
@var{dest-chars}の文字に変換します．

@c Instances of the @code{/} (or whatever other character is used in its stead),
@c @code{\}, or newlines can appear in the @var{source-chars} or @var{dest-chars}
@c lists, provide that each instance is escaped by a @code{\}.
@c The @var{source-chars} and @var{dest-chars} lists @emph{must}
@c contain the same number of characters (after de-escaping).
@c 
@code{/}(またはそのかわりに使用されている文字)，@code{\}，または改行のイ
ンスタンスは，それぞれのインスタンスに@code{\}でエスケープを提供すること
で@var{source-chars}や@var{dest-chars}のリストに書くことが可能です．
@var{source-chars}と@var{dest-chars}のリストには，(エスケープを取り除く
と)同じ数の文字を含める@emph{必要があります}．

@item a\
@itemx @var{text}
@c [At most one address allowed.]
@c 
[最大一つのアドレスが利用可能です．]

@findex a (append text lines) command
@cindex Appending text after a line
@cindex Text, appending
@c Queue the lines of text which follow this command
@c (each but the last ending with a @code{\},
@c which will be removed from the output)
@c to be output at the end of the current cycle,
@c or when the next input line is read.
@c 
このコマンドに続いているテキストの行(最後が@code{\}で終っているものは，
出力から取り除かれます)を，現在のサイクルの終りや，次の入力行が読み込ま
れたときに出力されるキューに保存します．

@c As a @sc{gnu} extension, if between the @code{a} and the newline there is
@c other than a whitespace-@code{\} sequence, then the text of this line,
@c starting at the first non-whitespace character after the @code{a},
@c is taken as the first line of the @var{text} block.
@c (This enables a simplification in scripting a one-line add.)
@c This extension also works with the @code{i} and @code{c} commands.
@c 
@sc{gnu}の拡張として，@code{a}と改行の間に空白と@code{\}の連続がある場合，
@code{a}の後の最初の空白文字以外で始まるこの行のテキストは，@var{text}ブ
ロックの最初の行として受けとられます．(これで，単純に一行のスクリプトを
追加するだけで可能になります．)この拡張は，@code{i}と@code{c}コマンドを
用いても動作します．

@item i\
@itemx @var{text}
@c [At most one address allowed.]
@c 
[最大一つのアドレスが利用可能です．]

@findex i (insert text lines) command
@cindex Inserting text before a line
@cindex Text, insertion
@c Immediately output the lines of text which follow this command
@c (each but the last ending with a @code{\},
@c which will be removed from the output).
@c 
このコマンドに続いている行(最後が@code{\}で終っているものは，出力から取
り除かれます)をすぐに出力します．

@item c\
@itemx @var{text}
@findex c (change to text lines) command
@cindex Replacing selected lines with other text
@c Delete the lines matching the address or address-range,
@c and output the lines of text which follow this command
@c (each but the last ending with a @code{\},
@c which will be removed from the output)
@c in place of the last line
@c (or in place of each line, if no addresses were specified).
@c A new cycle is started after this command is done,
@c since the pattern space will have been deleted.
@c 
マッチしたアドレスやアドレスの範囲の行を削除し，このコマンドに続いている
行(最後が@code{\}で終っているものは，出力から取り除かれます)を，最後の行
の位置(または，アドレスが指定されていない場合はそれぞれの行の位置)に出力
します．新しいサイクルは，パターンスペースが削除されてから，このコマンド
終了後に開始されます．

@item =
@c [At most one address allowed.]
@c 
[最大一つのアドレスが利用可能です．]

@findex = (print line number) command
@cindex Printing line number
@cindex Line number, printing
@c Print out the current input line number (with a trailing newline).
@c 
現在の入力行の行数を(改行を追加して)出力します．

@item l @var{n}
@findex l (list unambiguously) command
@cindex List pattern space
@cindex Printing text unambiguously
@cindex Line length, setting
@cindex @value{SSEDEXT}, setting line length
@c Print the pattern space in an unambiguous form:
@c non-printable characters (and the @code{\} character)
@c are printed in C-style escaped form; long lines are split,
@c with a trailing @code{\} character to indicate the split;
@c the end of each line is marked with a @code{$}.
@c 
明確な様式でパターンスペースを出力します．出力不可能な文字(と@code{\}文
字)は，Cの形式でエスケープされた様式で出力されます．長い行は分割を示す
@code{\}を後置して分割されます．それぞれの行の終りには@code{$}で印が付き
ます．

@c @var{n} specifies the desired line-wrap length;
@c a length of 0 (zero) means to never wrap long lines.  If omitted,
@c the default as specified on the command line is used.  The @var{n}
@c parameter is a @value{SSED} extension.
@c 
@var{n}は，要求される行を丸める長さを指定します．0(ゼロ)の長さは長い行を
丸めないことを意味します．省略されている場合，コマンドラインで指定されて
いるものがデフォルトとして使用されます．@var{n}パラメータは@value{SSED}
の拡張です．

@item L @var{n}
@findex L (fLow paragraphs) command
@cindex Reformat pattern space
@cindex Reformatting paragraphs
@cindex @value{SSEDEXT}, reformatting paragraphs
@cindex @value{SSEDEXT}, @code{L} command
@c This @value{SSED} extension fills and joins lines in pattern space
@c to produce output lines of (at most) @var{n} characters, like
@c @code{fmt} does; if @var{n} is omitted, the default as specified
@c on the command line is used.
@c 
この@value{SSED}の拡張は，@code{fmt}が行なうように，(最大)@var{n}文字の
行の出力を生成するため，パターンスペースの行を補充しつなげます．@var{n} 
が省略されている場合，コマンドラインで指定されているデフォルトを使用しま
す．

@c Blank lines, spaces between words, and indentation are
@c preserved in the output; successive input lines with different
@c indentation are not joined; tabs are expanded to 8 columns.
@c 
ブランク行，単語の間のスペース，そして字下げは出力で維持されます．異なる
字下げが連続している入力行はつなげられません．タブは八列に展開されます．

@c If pattern space contains multiple lines, they are joined, but
@c since pattern space usually contains a single line, the behavior
@c of a simple @code{L;d} script is the same as @code{fmt -s} (i.e.
@c it does not join short lines to form longer ones).
@c 
パターンスペースに複数の行が含まれている場合，それらはつなげられますが，
パターンスペースは通常単一行を含んでいるので，単純な@code{L;d}スクリプト
の動作は@code{fmt -s}と同じです(すなわち，短い行を長い行の形式につなげま
せん)．

@c @var{n} specifies the desired line-wrap length; if omitted,
@c the default as specified on the command line is used.
@c 
@var{n}は，行を丸める長さを指定することを要求します．省略されている場合，
コマンドラインで指定されているデフォルトを使用します．

@item r @var{filename}
@c [At most one address allowed.]
@c 
[最大一つのアドレスが利用可能です．]

@findex r (read file) command
@cindex Read text from a file
@cindex @value{SSEDEXT}, @file{/dev/stdin} file
@c Queue the contents of @var{filename} to be read and
@c inserted into the output stream at the end of the current cycle,
@c or when the next input line is read.
@c Note that if @var{filename} cannot be read, it is treated as
@c if it were an empty file, without any error indication.
@c 
@var{filename}の内容を読み込み，，現在のサイクルの終りや次の入力行が読み
込まれたときに出力ストリームに挿入するためキューに保存します．
@var{filename}が読み込み不可能な場合，エラーを示すことなく空のファイルが
読み込まれているかのように扱われることに注意してください．

@c As a @value{SSED} extension, the special value @file{/dev/stdin}
@c is supported for the file name, which reads the contents of the
@c standard input.
@c 
@value{SSED}の拡張として，特殊な値@file{/dev/stdin}がファイル名としてサ
ポートされていて，それは標準入力の内容を読み込みます．

@item R @var{filename}
@findex R (read line) command
@cindex Read text from a file
@cindex @value{SSEDEXT}, reading a file a line at a time
@cindex @value{SSEDEXT}, @code{R} command
@cindex @value{SSEDEXT}, @file{/dev/stdin} file
@c Queue a line of @var{filename} to be read and
@c inserted into the output stream at the end of the current cycle,
@c or when the next input line is read.
@c Note that if @var{filename} cannot be read, or if its end is
@c reached, no line is appended, without any error indication.
@c 
@var{filename}の行を読み込み，，現在のサイクルの終りや次の入力行が読み込
まれたときに出力ストリームに挿入するためキューに保存します．
@var{filename}が読み込み不可能，またはファイルの終りに達した場合，エラー
を示すことなく行が追加されないことに注意してください．

@c As with the @code{r} command, the special value @file{/dev/stdin}
@c is supported for the file name, which reads a line from the
@c standard input.
@c 
@code{r}コマンド同様，特殊な値@file{/dev/stdin}がファイル名としてサポー
トされていて，それは標準入力の内容を読み込みます．

@item w @var{filename}
@findex w (write file) command
@cindex Write to a file
@cindex @value{SSEDEXT}, @file{/dev/stdout} file
@cindex @value{SSEDEXT}, @file{/dev/stderr} file
@c Write the pattern space to @var{filename}.
@c As a @value{SSED} extension, two special values of @var{file-name} are
@c supported: @file{/dev/stderr}, which writes the result to the standard
@c error, and @file{/dev/stdout}, which writes to the standard
@c output.@footnote{This is equivalent to @code{p} unless the @code{-i}
@c switch is being used.}
@c 
パターンスペースを@var{filename}に書き出します．@value{SSED}の拡張として，
@var{file-name}として二つの特殊な値がサポートされています．
@file{/dev/stderr}は結果を標準エラー出力に書き出し，@file{/dev/stdout}は
標準出力に書き出します．@footnote{@code{-i}スイッチが使用されていない限
り，これは@code{p}と等価です．}

@c The file will be created (or truncated) before the
@c first input line is read; all @code{w} commands
@c (including instances of @code{w} flag on successful @code{s} commands)
@c which refer to the same @var{filename} are output without
@c closing and reopening the file.
@c 
最初の入力行が読み込まれる前に，ファイルは作成され(または切り詰められ)ま
す．同じ@var{filename}を参照するすべての@code{w}コマンドは(@code{s}コマ
ンド成功時の@code{w}フラグのインスタンスを含めて)，ファイルを閉じ再び開
くこと無く出力されます．

@item D
@findex D (delete first line) command
@cindex Delete first line from pattern space
@c Delete text in the pattern space up to the first newline.
@c If any text is left, restart cycle with the resultant
@c pattern space (without reading a new line of input),
@c otherwise start a normal new cycle.
@c 
パターンスペースのテキストを最初の改行まで削除します．テキストが残ってい
る場合，(入力の新しい行を読み込むことなく)結果として生じているパターンス
ペースでサイクルを再び開始し，それ以外では通常通り新しいサイクルを開始し
ます．

@item N
@findex N (append Next line) command
@cindex Next input line, append to pattern space
@cindex Append next input line to pattern space
@c Add a newline to the pattern space,
@c then append the next line of input to the pattern space.
@c If there is no more input then @code{sed} exits without processing
@c any more commands.
@c 
パターンスペースに改行を追加し，入力の次の行をパターンスペースに後置しま
す．入力がそれ以上ない場合，@code{sed}は終了しそれ以上のコマンドを処理し
ません．

@item P
@findex P (print first line) command
@cindex Print first line from pattern space
@c Print out the portion of the pattern space up to the first newline.
@c 
パターンスペースの位置を最初の改行まで出力します．

@item h
@findex h (hold) command
@cindex Copy pattern space into hold space
@cindex Replace hold space with copy of pattern space
@cindex Hold space, copying pattern space into
@c Replace the contents of the hold space with the contents of the pattern space.
@c 
ホールドスペースの内容をパターンスペースの内容で置換します．

@item H
@findex H (append Hold) command
@cindex Append pattern space to hold space
@cindex Hold space, appending from pattern space
@c Append a newline to the contents of the hold space,
@c and then append the contents of the pattern space to that of the hold space.
@c 
ホールドスペースの内容に改行を後置した後，パターンスペースの内容をホール
ドスペースに後置します．

@item g
@findex g (get) command
@cindex Copy hold space into pattern space
@cindex Replace pattern space with copy of hold space
@cindex Hold space, copy into pattern space
@c Replace the contents of the pattern space with the contents of the hold space.
@c 
パターンスペースの内容をホールドスペースの内容で置換します．

@item G
@findex G (appending Get) command
@cindex Append hold space to pattern space
@cindex Hold space, appending to pattern space
@c Append a newline to the contents of the pattern space,
@c and then append the contents of the hold space to that of the pattern space.
@c 
パターンスペースの内容に改行を後置した後，ホールドスペースの内容をパター
ンスペースに後置します．

@item x
@findex x (eXchange) command
@cindex Exchange hold space with pattern space
@cindex Hold space, exchange with pattern space
@c Exchange the contents of the hold and pattern spaces.
@c 
ホールドスペースとパターンスペースの内容を入れ換えます．

@end table


@node Programming Commands
@c @section Commands for @code{sed} gurus
@section @code{sed}のベテランプログラマのためのコマンド

@c In most cases, use of these commands indicates that you are
@c probably better off programming in something like @code{awk}
@c or Perl.  But occasionally one is committed to sticking
@c with @code{sed}, and these commands can enable one to write
@c quite convoluted scripts.
@c 
ほとんどの状況で，これらのコマンドを使用するよりは，おそらく@code{awk}や
Perlのようなものでプログラムをした方が良いでしょう．しかし，時には
@code{sed}に執念を燃やす人もいて，これらのコマンドで全く複雑なスクリプト
を書くことも可能になります．

@cindex Flow of control in scripts
@table @samp
@item : @var{label}
@c [No addresses allowed.]
@c 
[アドレスは利用不可能です．]

@findex : (label) command
@cindex Labels, in scripts
@c Specify the location of @var{label} for branch commands.
@c In all other respects, a no-op.
@c 
条件分岐コマンドに対する@var{label}の位置を指定します．それ以外では何も
しません．

@item b @var{label}
@findex b (branch) command
@cindex Branch to a label, unconditionally
@cindex Goto, in scripts
@c Unconditionally branch to @var{label}.
@c The @var{label} may be omitted, in which case the next cycle is started.
@c 
無条件で@var{label}に分岐します．@var{label}は省略可能で，その場合は次の
サイクルが開始されます．

@item t @var{label}
@findex t (test and branch if successful) command
@cindex Branch to a label, if @code{s///} succeeded
@cindex Conditional branch
@c Branch to @var{label} only if there has been a successful @code{s}ubstitution
@c since the last input line was read or conditional branch was taken.
@c The @var{label} may be omitted, in which case the next cycle is started.
@c 
前回の入力行の読み込みや条件分岐が行なわれてから，@code{s}の置換で成功し
たしたものがある場合のみ@var{label}に分岐します．@var{label}は省略可能で，
その場合は次のサイクルが開始されます．

@item T @var{label}
@findex T (test and branch if failed) command
@cindex @value{SSEDEXT}, branch if @code{s///} failed
@cindex Branch to a label, if @code{s///} failed
@cindex Conditional branch
@c Branch to @var{label} only if there have been no successful
@c @code{s}ubstitutions since the last input line was read or
@c conditional branch was taken. The @var{label} may be omitted,
@c in which case the next cycle is started.
@c 
前回の入力行の読み込みや条件分岐が行なわれてから，@code{s}の置換で成功し
なかったものがある場合のみ@var{label}に分岐します．@var{label}は省略可能
で，その場合は次のサイクルが開始されます．

@end table

@node SSED-specific Commands
@c @section Commands specific of @value{SSED}
@section @value{SSED}特有のコマンド

@c These commands are specific of @value{SSED}, so you
@c must use them with care and only when you are sure that
@c hindering portability is not so evil.  They allow to check
@c for @value{SSED} extensions or to do tasks that are required
@c quite often, yet unsupported by standard @code{sed}s.
@c 
以下のコマンドは@value{SSED}特有なので，注意して使用する必要があり，移植
性の邪魔になると分かっているときだけ使用することはそう悪いものではありま
せん．それらで@value{SSED}の拡張を調査したり，標準的な@code{sed}ではまだ
サポートされていないが，よく要求される作業を行なうことが可能になります．

@table @code
@item v
@findex v (version) command
@cindex @value{SSEDEXT}, checking for their presence
@cindex Requiring @value{SSED}
@c This command does nothing, but will make @code{sed} fail if
@c @value{SSED} extensions are not supported, simply because other
@c implementations of @code{sed} do not implement it.
@c 
このコマンドは何もしませんが，@value{SSED}の拡張がサポートされていない場
合は@code{sed}は異常終了し，それはその他の@code{sed}の実装ではそれを実装
していないためです．

@item Q [@var{exit-code}]
@findex Q (silent Quit) command
@cindex @value{SSEDEXT}, quitting silently
@cindex @value{SSEDEXT}, returning an exit code
@cindex Quitting
@c This command is the same as @code{q}, but will not print the
@c contents of pattern space.  Like @code{q}, it provides the
@c ability to return an exit code to the caller.
@c 
このコマンドは@code{q}と同じですが，パターンスペースの内容を出力しません．
@code{q}に似ていて，呼び出し側に終了コードを返す能力を提供しています．

@c This command can be useful because the only alternative ways
@c to accomplish this apparently trivial function are to use
@c the @code{-n} option (which can unnecessarily complicate
@c your script) or resorting to the following snippet, which
@c wastes time by reading the whole file without any visible effect:
@c 
この一見些細な機能を達成する唯一の別の方法は，@code{-n}オプションを使用
する方法(スクリプトが不必要に複雑になります)や，見た目に影響しないように
ファイル全体を読み込むと時間が無駄になるような以下の断片を利用する方法な
ので，役に立つはずです．

@example
:eat
$d       # @r{Quit silently on the last line}
N        # @r{Read another line, silently}
g        # @r{Overwrite pattern space each time to save memory}
b eat
@end example

@item T @var{label}
@findex T (test and branch if failed) command
@cindex @value{SSEDEXT}, branch if @code{s///} failed
@cindex Branch to a label, if @code{s///} failed
@cindex Conditional branch
@c Branch to @var{label} only if there have been no successful
@c @code{s}ubstitutions since the last input line was read or
@c conditional branch was taken. The @var{label} may be omitted,
@c in which case the next cycle is started.
@c 
前回の入力行の読み込みや条件分岐が行なわれてから，@code{s}の置換で成功し
なかったものがある場合のみ@var{label}に分岐します．@var{label}は省略可能
で，その場合は次のサイクルが開始されます．

@item e [@var{command}]
@findex e (evaluate) command
@cindex Evaluate Bourne-shell commands
@cindex Subprocesses
@cindex @value{SSEDEXT}, evaluating Bourne-shell commands
@cindex @value{SSEDEXT}, subprocesses
@c This command allows one to pipe input from a shell command
@c into pattern space.  Without parameters, the @code{e} command
@c executes the command that is found in pattern space and
@c replaces pattern space with the output; a trailing new-line
@c is suppressed.
@c 
このコマンドで，シェルコマンドからの入力をパターンスペースへのパイプで渡
すことが可能になります．パラメータを用いていない場合，@code{e}コマンドは
パターンスペースで見つかったコマンドを実行し，パターンスペースを出力で置
換します．後置される改行は抑制されます．

@c If a parameter is specified, instead, the @code{e} command
@c interprets it as a command and sends it to the output stream
@c (like @code{r} does).  The command can run across multiple
@c lines, all but the last ending with a back-slash.
@c 
パラメータが指定されている場合は，代わりに@code{e}コマンドがそれをコマン
ドとして解釈し，(@code{r}が行なうように)それを出力ストリームに送ります．
そのコマンドは，最後の終りがバックスラッシュでない限り，複数の行を跨って
実行することが可能です．

@c In both cases, results are undefined if the command to be
@c executed contains a @code{nul} character.
@c 
いずれの場合でも，実行されたコマンドに@code{nul}文字が含まれる場合，結果
は定義されていません．

@item W @var{filename}
@findex W (write first line) command
@cindex Write first line to a file
@cindex @value{SSEDEXT}, writing first line to a file
@c Write to the given filename the portion of the pattern space up to
@c the first newline.  Everything said under the @code{w} command about
@c file handling holds here too.
@c 
最初の改行までのパターンスペースの位置を与えられた@var{filename}に書き出
します．ここでのファイル処理は@code{w}コマンドですべて述べています．

@item L @var{n}
@findex L (fLow paragraphs) command
@cindex Reformat pattern space
@cindex Reformatting paragraphs
@cindex @value{SSEDEXT}, reformatting paragraphs
@cindex @value{SSEDEXT}, @code{L} command
@c This @value{SSED} extension fills and joins lines in pattern space
@c to produce output lines of (at most) @var{n} characters, like
@c @code{fmt} does; if @var{n} is omitted, the default as specified
@c on the command line is used.
@c 
この@value{SSED}の拡張は，@code{fmt}が行なうように，(最大)@var{n}文字の
行の出力を生成するため，パターンスペースの行を補充しつなげます．@var{n} 
が省略されている場合，コマンドラインで指定されているデフォルトを使用しま
す．

@c Blank lines, spaces between words, and indentation are
@c preserved in the output; successive input lines with different
@c indentation are not joined; tabs are expanded to 8 columns.
@c 
ブランク行，単語の間のスペース，そして字下げは出力で維持されます．異なる
字下げが連続している入力行はつなげられません．タブは八列に展開されます．

@c If pattern space contains multiple lines, they are joined, but
@c since pattern space usually contains a single line, the behavior
@c of a simple @code{L;d} script is the same as @code{fmt -s} (i.e.
@c it does not join short lines to form longer ones).
@c 
パターンスペースに複数の行が含まれている場合，それらはつなげられますが，
パターンスペースは通常単一行を含んでいるので，単純な@code{L;d}スクリプト
の動作は@code{fmt -s}と同じです(すなわち，短い行を長い行の形式につなげま
せん)．

@c @var{n} specifies the desired line-wrap length; if omitted,
@c the default as specified on the command line is used.
@c 
@var{n}は，行を丸める長さの指定を要求します．省略されている場合，コマン
ドラインで指定されているデフォルトを使用します．

@item R @var{filename}
@findex R (read line) command
@cindex Read text from a file
@cindex @value{SSEDEXT}, reading a file a line at a time
@cindex @value{SSEDEXT}, @code{R} command
@cindex @value{SSEDEXT}, @file{/dev/stdin} file
@c Queue a line of @var{filename} to be read and
@c inserted into the output stream at the end of the current cycle,
@c or when the next input line is read.
@c Note that if @var{filename} cannot be read, or if its end is
@c reached, no line is appended, without any error indication.
@c 
@var{filename}の行を読み込み，，現在のサイクルの終りや次の入力行が読み込
まれたときに出力ストリームに挿入するためキューに保存します．
@var{filename}が読み込み不可能，またはファイルの終りに達した場合，エラー
を示すことなく行が追加されないことに注意してください．

@c As with the @code{r} command, the special value @file{/dev/stdin}
@c is supported for the file name, which reads a line from the
@c standard input.
@c 
@code{r}コマンド同様，特殊な値@file{/dev/stdin}がファイル名としてサポー
トされていて，それは標準入力の内容を読み込みます．

@end table

@node Escapes
@c @section @sc{gnu} extensions for escapes in regular expressions
@section 正規表現でのエスケープに関する@sc{gnu}の拡張

@cindex @acronym{GNU} extensions, special escapes
@c Until this chapter, you have only encountered escapes of the form
@c @samp{\^}, which tell @code{sed} not to interpret the caret
@c as a special character, but rather to take it literally.  For
@c example, @samp{\*} matches a single asterisk rather than zero
@c or more backslashes.
@c 
この章まで，@code{sed}にキャレットを特殊文字でなく文字通りに解釈するよう
に伝える@samp{\^}の形式のエスケープだけを見てきました．例えば，@samp{\*} 
はゼロ以上のバックスラッシュでは無く単一のアスタリスクにマッチします．

@cindex @code{POSIXLY_CORRECT} behavior, escapes
@c This chapter introduces another kind of escapes@footnote{All
@c the escapes that are introduced in this character are@sc{gnu}
@c extensions, with the exception of @code{\n}.  In basic regular
@c expression mode, setting @code{POSIXLY_CORRECT} disables them.}---that
@c is, escapes that are applied to a character or sequence of characters
@c that ordinarily is taken literally, and that @code{sed} replaces
@c with a special character.  This provides a way
@c of encoding non-printable characters in patterns in a visible manner.
@c There is no restriction on the appearance of non-printing characters
@c in a @code{sed} script but when a script is being prepared in the
@c shell or by text editing, it is usually easier to use one of
@c the following escape sequences than the binary character it
@c represents:
@c 
この章では，他の種類のエスケープを紹介します@footnote{この章で紹介するす
べてのエスケープは，@code{\n}以外@sc{gnu}の拡張です．基本正規表現モード
では，@code{POSIXLY_CORRECT}を設定することで，それらを利用することができ
なくなります．} --- すなわち，通常の文字や文字の連続に適用されるエスケー
プは文字通りに受けとられ，@code{sed}は特殊文字で置換します．これは，パター
ンスペースの印刷不可能な文字を目に見える方法でエンコードする方法を提供し
ます．@code{sed}スクリプト内での印刷不可能な文字の存在に制限はありません
が，スクリプトがシェルやテキストの編集で準備されるとき，バイナリ文字で表
現するより，以下のエスケープシーケンスの一つを使用する方が通常は簡単です．

@c The list of these escapes is:
@c 
これらのエスケープのリストは以下にあります．

@table @samp
@item \a
@c Produces or matches a @sc{bel} character, that is an ``alert'' (@sc{ascii} 7).
@c 
@sc{bel}文字を生成またはそれにマッチし，それは``アラート''(@sc{ascii} 7)
です．

@item \f
@c Produces or matches a form feed (@sc{ascii} 12).
@c 
フォームフィードを生成またはそれにマッチします(@sc{ascii} 12)．

@item \n
@c Produces or matches a new-line (@sc{ascii} 10).
@c 
改行を生成またはそれにマッチします(@sc{ascii} 10)．

@item \r
@c Produces or matches a carriage return (@sc{ascii} 13).
@c 
キャリッジリターンを生成またはそれにマッチします(@sc{ascii} 13)．

@item \t
@c Produces or matches a horizontal tab (@sc{ascii} 9).
@c 
水平タブを生成またはそれにマッチします(@sc{ascii} 9)．

@item \v
@c Produces or matches a so called ``vertical tab'' (@sc{ascii} 11).
@c 
``垂直タブ''と呼ばれるものを生成またはそれにマッチします(@sc{ascii} 11)．

@item \c@var{x}
@c Produces or matches @kbd{@sc{Control}-@var{x}}, where @var{x} is
@c any character.  The precise effect of @samp{\c@var{x}} is as follows:
@c if @var{x} is a lower case letter, it is converted to upper case.
@c Then bit 6 of the character (hex 40) is inverted.  Thus "\cz" becomes
@c hex 1A, but @samp{\c@{} becomes hex 3B, while @samp{\c;} becomes hex 7B.
@c 
@kbd{@sc{Control}-@var{x}}を生成またはそれにマッチし，@var{x}は任意の文
字です．@samp{\c@var{x}}の明確な効果は以下のようになります．@var{x}が小
文字の場合，それは大文字に変換されます．文字のビットの6(16進数の40)が反
転します．このため，"\cz"は16進数の1Aになりますが，@samp{\c@{}は16進数の
3Bになり，@samp{\c;} は16進数の7Bになります．

@item \d@var{xxx}
@c Produces or matches a character whose decimal @sc{ascii} value is @var{xxx}.
@c 
十進数の@sc{ascii}値が@var{xxx}の文字を生成またはそれにマッチします．

@item \o@var{xxx}
@ifset PERL
@item \@var{xxx}
@end ifset
@c Produces or matches a character whose octal @sc{ascii} value is @var{xxx}.
@c 
八進数の@sc{ascii}値が@var{xxx}の文字を生成またはそれにマッチします．

@ifset PERL
@c The syntax without the @code{o} is active in Perl mode, while the one
@c with the @code{o} is active in the normal or extended @sc{posix} regular
@c expression modes.
@c 
@code{o}を用いない構文はパールモードで動作しますが，@code{o}を用いたもの
は通常の，または拡張された@sc{posix}正規表現モードで動作します．
@end ifset

@item \x@var{xx}
@c Produces or matches a character whose hexadecimal @sc{ascii} value is @var{xx}.
@c 
16進数の@sc{ascii}値が@var{xx}の文字を生成またはそれにマッチします．

@end table

@c @samp{\b} (backspace) was omitted because of the conflict with
@c the existing "word boundary" meaning.
@c 
@samp{\b}(バックスラッシュ)は，既存の"単語の境界"の意味と衝突するので削
除されています．

@c Other escapes match particular character class and are only valid in
@c regular expressions:
@c 
それ以外のエスケープは特定の文字集合にマッチし，正規表現内だけで有効です．

@table @samp
@item \s
@c Matches any whitespace character
@c 
空白文字にマッチします．

@item \S
@c Matches any character that is not a whitespace character
@c 
空白文字以外の文字にマッチします．

@item \w
@c Matches any ``word'' character.  A ``word'' character is any
@c letter or digit or the underscore character.
@c 
あらゆる``単語''文字にマッチします．``単語''文字とはすべての文字と数字と
アンダースコアです．

@item \W
@c Matches any ``non-word'' character
@c 
``単語以外''の文字にマッチします．
@end table

@node Examples
@c @chapter Some sample scripts
@chapter いくつかの見本スクリプト

@c Here are some @code{sed} scripts to guide you in the art of mastering
@c @code{sed}...
@c 
以下は，@code{sed}をマスターするためのガイドとなるいくつかの@code{sed}ス
クリプトの@enddots{}

@menu
Some exotic examples:
* Centering lines::
* Increment a number::
* Rename files to lower case::
* Print bash environment::
* Reverse chars of lines::

Emulating standard utilities:
* tac::                             Reverse lines of files
* cat -n::                          Numbering lines
* cat -b::                          Numbering non-blank lines
* wc -c::                           Counting chars
* wc -w::                           Counting words
* wc -l::                           Counting lines
* head::                            Printing the first lines
* tail::                            Printing the last lines
* uniq::                            Make duplicate lines unique
* uniq -d::                         Print duplicated lines of input
* uniq -u::                         Remove all duplicated lines
* cat -s::                          Squeezing blank lines
@end menu

@node Centering lines
@c @section Centering lines
@section 行の中央揃え

@c This script will center all lines of a file on a 80 columns width.
@c To change that width, the number in @code{\@{\@}} must be
@c replaced, and the number of added spaces also must be changed.
@c 
以下のスクリプトは，ファイルのすべての行を80桁の幅でセンタリングします．
幅を変更するため，@code{\@{\@}}の数値を変更する必要があり，追加されるス
ペースも変更する必要があります．

@c Note how the buffer commands are used to separate parts in
@c the regular expressions to be matched---this is a common
@c technique.
@c 
マッチさせる正規表現の部分を分離するため，バッファコマンドが使用されてい
る方法に注意してください --- これは一般的なテクニックです．

@c start-------------------------------------------
@example
#!/usr/bin/sed -f

@group
#@r{ Put 80 spaces in the buffer}
1 @{
  x
  s/^$/          /
  s/^.*$/&&&&&&&&/
  x
@}
@end group

@group
#@r{ del leading and trailing spaces}
y/@kbd{tab}/ /
s/^ *//
s/ *$//
@end group

@group
#@r{ add a new-line and 80 spaces to end of line}
G
@end group

@group
#@r{ keep first 81 chars (80 + a new-line)}
s/^\(.\@{81\@}\).*$/\1/
@end group

@group
#@r{ \2 matches half of the spaces, which are moved to the beginning}
s/^\(.*\)\n\(.*\)\2/\2\1/
@end group
@end example
@c end---------------------------------------------

@node Increment a number
@c @section Increment a number
@section 数字を増加させる

@c This script is one of a few that demonstrate how to do arithmetic
@c in @code{sed}.  This is indeed possible@footnote{@code{sed} guru Greg
@c Ubben wrote an implementation of the @code{dc} @sc{rpn} calculator!
@c It is distributed together with sed.}, but must be done manually.
@c 
以下のスクリプトは，@code{sed}で算数を行なう方法を説明するものの一つです．
これは実際には可能ですが@footnote{@code{sed}のベテランGreg Ubbenは，
@code{dc} @sc{rpn}の計算機の実装を書いています！それはsedとともに配布さ
れています．}，手動で行なうべきでしょう．

@c To increment one number you just add 1 to last digit, replacing
@c it by the following digit.  There is one exception: when the digit
@c is a nine the previous digits must be also incremented until you
@c don't have a nine.
@c 
数値を一つ増加させるには，最後の桁に1を追加し，それに続く桁を置換するだ
けです．例外が一つあります．その桁の前の数値が9のとき，9が無くなるまで増
加させる必要もあります．

@c This solution by Bruno Haible is very clever and smart because
@c it uses a single buffer; if you don't have this limitation, the
@c algorithm used in @ref{cat -n, Numbering lines} is faster.
@c It works by replacing trailing nines with an underscore, then
@c using multiple @code{s} commands to increment the last digit,
@c and then again substituting underscores with zeros.
@c 
このBruno Haibleによる解決方法は，単一のバッファを使用しているので非常に
賢く知的です．この制限がない場合，@ref{cat -n, Numbering lines}で使用さ
れているアルゴリズムの方がより速いでしょう．それは後置される9をアンダー
スコアで置換し，複数の@code{s}コマンドを最後の桁を増加させるために使用し，
そして，再びアンダースコアをゼロで置換することで動作します．

@c start-------------------------------------------
@example
#!/usr/bin/sed -f

/[^0-9]/ d

@group
#@r{ replace all leading 9s by _ (any other char except digits, could}
#@r{ be used)}
:d
s/9\(_*\)$/_\1/
td
@end group

@group
#@r{ incr last digit only.  The first line adds a most-significant}
#@r{ digit of 1 if we have to add a digit.}
#@r{}
#@r{ The @code{tn} commands are not necessary, but make the thing}
#@r{ faster}
@end group

@group
s/^\(_*\)$/1\1/; tn
s/8\(_*\)$/9\1/; tn
s/7\(_*\)$/8\1/; tn
s/6\(_*\)$/7\1/; tn
s/5\(_*\)$/6\1/; tn
s/4\(_*\)$/5\1/; tn
s/3\(_*\)$/4\1/; tn
s/2\(_*\)$/3\1/; tn
s/1\(_*\)$/2\1/; tn
s/0\(_*\)$/1\1/; tn
@end group

@group
:n
y/_/0/
@end group
@end example
@c end---------------------------------------------

@node Rename files to lower case
@c @section Rename files to lower case
@section ファイル名を小文字に変更する

@c This is a pretty strange use of @code{sed}.  We transform text, and
@c transform it to be shell commands, then just feed them to shell.
@c Don't worry, even worse hacks are done when using @code{sed}; I have
@c seen a script converting the output of @code{date} into a @code{bc}
@c program!
@c  
以下はちょっと変わった@code{sed}の使用方法です．我々はテキストを変換し，
それをシェルコマンドに変換し，そしてそれらをそのままシェルに与えます．
@code{sed}を使用するとき，更に悪いことになっても気にしないでください．
@code{date}の出力を@code{bc}プログラムに変換するスクリプトを見たことだっ
てあります！

@c The main body of this is the @code{sed} script, which remaps the name
@c from lower to upper (or vice-versa) and even checks out 
@c if the remapped name is the same as the original name.
@c Note how the script is parameterized using shell
@c variables and proper quoting.
@c 
これのメインの本体は@code{sed}スクリプトで，名前を小文字から大文字(また
はその逆に)に置き換え，置き換えられた名前がオリジナルの名前と同じ場合で
も適用します．スクリプトがシェル変数を使用して媒介している方法と，適切に
引用符で囲んでいる方法に注意してください．

@c start-------------------------------------------
@example
@group
#! /bin/sh
#@r{ rename files to lower/upper case... }
#@r{}
#@r{ usage: }
#@r{    move-to-lower * }
#@r{    move-to-upper * }
#@r{ or}
#@r{    move-to-lower -R .}
#@r{    move-to-upper -R .}
#@r{}	
@end group

@group
help()
@{
	cat << eof
Usage: $0 [-n] [-r] [-h] files...
@end group

@group
-n      do nothing, only see what would be done
-R      recursive (use find)
-h      this message
files   files to remap to lower case
@end group

@group
Examples:
       $0 -n *        (see if everything is ok, then...)
       $0 *
@end group

       $0 -R .

@group
eof
@}
@end group

@group
apply_cmd='sh'
finder='echo $* | tr " " "\n"'
files_only=
@end group

@group
while :
do
    case "$1" in 
        -n) apply_cmd='cat' ;;
        -R) finder='find $* -type f';;
        -h) help ; exit 1 ;;
        *) break ;;
    esac
    shift
done
@end group

@group
if [ -z "$1" ]; then
        echo Usage: $0 [-n] [-r] files...
        exit 1
fi
@end group

@group
LOWER='abcdefghijklmnopqrstuvwxyz'
UPPER='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
@end group

@group
case `basename $0` in
        *upper*) TO=$UPPER; FROM=$LOWER ;;
        *)       FROM=$UPPER; TO=$LOWER ;;
esac
@end group
	
eval $finder | sed -n '

@group
#@r{ remove all trailing slashes}
s/\/*$//
@end group

@group
#@r{ add ./ if there are no path, only filename}
/\//! s/^/.\//
@end group

@group
#@r{ save path+filename}
h
@end group

@group
#@r{ remove path}
s/.*\///
@end group

@group
#@r{ do conversion only on filename}
y/'$FROM'/'$TO'/
@end group

@group
#@r{ now line contains original path+file, while}
#@r{ hold space contains the new filename}
x
@end group

@group
#@r{ add converted file name to line, which now contains}
#@r{ @var{path}/@var{file-name}\n@var{converted-file-name}}
G
@end group

@group
#@r{ check if converted file name is equal to original file name,}
#@r{ if it is, do not print nothing}
/^.*\/\(.*\)\n\1/b
@end group

@group
#@r{ now, transform @code{@var{path}/@var{fromfile}\n@var{tofile}}, into}
#@r{ @code{mv @var{path}/@var{fromfile} @var{path}/@var{tofile}} and print it}
s/^\(.*\/\)\(.*\)\n\(.*\)$/mv \1\2 \1\3/p
@end group

' | $apply_cmd
@end example
@c end---------------------------------------------

@node Print bash environment
@c @section Print bash environment
@section @code{bash}の環境変数の出力

@c This script strips the definition of the shell functions
@c from the output of the @code{set} Bourne-shell command.
@c 
以下のスクリプトは，@code{set} Bourneシェルコマンドの出力から，シェル関
数の定義を取り除きます．

@c start-------------------------------------------
@example
#!/bin/sh

@group
set | sed -n '
:x
@end group

@group
#@r{ if no occurrence of @samp{=()} print and load next line}
/=() /! @{ p; b; @}
@end group

@group
#@r{ possible start of functions section}
#@r{ save the line in case this is a var like FOO="() "}
h
@end group

@group
#@r{ if the next line has a brace, we quit because}
#@r{ nothing comes after functions}
n
/^@{/ q
@end group

@group
#@r{ print the old line}
x; p
@end group

@group
#@r{ work on the new line now}
x; bx
'
@end group
@end example
@c end---------------------------------------------

@node Reverse chars of lines
@c @section Reverse chars of lines
@section 行の文字を反転する

@c This script can be used to reverse the position of characters
@c in lines.  The technique moves two characters at a time, hence
@c it is faster than more intuitive implementations.
@c 
以下のスクリプトは，行の文字の位置を反転するために使用することが可能です．
二つの文字を同時に移動するテクニックで，直観的な実装より高速になります．

@c Note the @code{tx} command before the definition of the label.
@c This is often needed to reset the flag that is tested by
@c the @code{t} command.
@c 
ラベル定義の前の@code{tx}コマンドに注意してください．これは@code{t}コマ
ンドでテストされるフラグをリセットするために必要になることがよくあります．

@c Imaginative readers will find uses to this script.  An example
@c is reversing the output of @code{banner}@footnote{This requires
@c another script to pad the output of banner; for example
@c 
想像力豊かな読者は，このスクリプトの使い方が分かるでしょう．例えば，
@code{banner}の出力を反転させることです@footnote{これは，@code{banner}の
出力を埋める他のスクリプトが必要です．例えば以下のようにします．

@example
#! /bin/sh

banner -w $1 $2 $3 $4 |
  sed -e :a -e '/^.\@{0,'$1'\@}$/ @{ s/$/ /; ba; @}' |
  ~/sedscripts/reverseline.sed
@end example
}．

@c start-------------------------------------------
@example
#!/usr/bin/sed -f

/../! b

@group
#@r{ Reverse a line.  Begin embedding the line between two new-lines}
s/^.*$/\
&\
/
@end group

@group
#@r{ Move first character at the end.  The regexp matches until}
#@r{ there are zero or one characters between the markers}
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx
@end group

@group
#@r{ Remove the new-line markers}
s/\n//g
@end group
@end example
@c end---------------------------------------------

@node tac
@c @section Reverse lines of files
@section ファイルの行を反転する

@c This one begins a series of totally useless (yet interesting)
@c scripts emulating various Unix commands.  This, in particular,
@c is a @code{tac} workalike.
@c 
以下のものは，様々なUnixコマンドをエミュレートする全く意味がない(面白い
けどね)スクリプトです．これは特に@code{tac}と同等の動作をします．

@c Note that on implementations other than @sc{gnu} @code{sed}
@c and @value{SSED} this script might easily overflow internal buffers.
@c 
@sc{gnu} @code{sed}と@value{SSED}以外の実装では，このスクリプトは簡単に
内部バッファでオーバーフローする可能性があることに注意してください．

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

#@r{ reverse all lines of input, i.e. first line became last, ...}

@group
#@r{ from the second line, the buffer (which contains all previous lines)}
#@r{ is *appended* to current line, so, the order will be reversed}
1! G
@end group

@group
#@r{ on the last line we're done -- print everything}
$ p
@end group

@group
#@r{ store everything on the buffer again}
h
@end group
@end example
@c end---------------------------------------------

@node cat -n
@c @section Numbering lines
@section 行の番号付け

@c This script replaces @code{cat -n}; in fact it formats its output
@c exactly like @sc{gnu} @code{cat} does.
@c 
以下のスクリプトは@code{cat -n}の置換えです．実際それは，出力を@sc{gnu}
@code{cat}のように正確に書式化します．

@c Of course this is completely useless and for two reasons:  first,
@c because somebody else did it in C, second, because the following
@c Bourne-shell script could be used for the same purpose and would
@c be much faster:
@c 
もちろん，これは二つの理由から全く意味がありません．まず始めに他のものは
Cで行ないます．二番目に以下のBourneシェルスクリプトは同じ目的で使用され，
はるかに速くなります．

@c start-------------------------------------------
@example
@group
#! /bin/sh
sed -e "=" $@@ | sed -e '
  s/^/      /
  N
  s/^ *\(......\)\n/\1  /
'
@end group
@end example
@c end---------------------------------------------

@c It uses @code{sed} to print the line number, then groups lines two
@c by two using N.  Of course, this script does not teach as much as
@c the one presented below.
@c 
それは行番号を出力するために@code{sed}を使用し，二つのNで行を二つにまと
めます．もちろん，このスクリプトは以下で提示するものほど教わるものはあり
ません．

@c The algorithm used for incrementing uses both buffers, so the line
@c is printed as soon as possible and then discarded.  The number
@c is split so that changing digits go in a buffer and unchanged ones go
@c in the other; the changed digits are modified in a single step
@c (using a @code{y} command).  The line number for the next line
@c is then composed and stored in hold space, to be used in the
@c next iteration.
@c 
増加で使用しているアルゴリズムを両方のバッファで使用しているので，行は可
能な限り速く出力され，そして破棄されます．数値は変更した桁がバッファに入
り，変更されないものがもう一方に行くように分離されています．変更される桁
は単一のステップ(@code{y}コマンドを使用して)修正されます．次の行の行番号
は，次の繰り返しで使用されるように，作成されホールドスペースに保存されま
す．

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

@group
#@r{ Prime the pump on the first line}
x
/^$/ s/^.*$/1/
@end group

@group
#@r{ Add the correct line number before the pattern}
G
h
@end group

@group
#@r{ Format it and print it}
s/^/      /
s/^ *\(......\)\n/\1  /p
@end group

@group
#@r{ Get the line number from hold space; add a zero}
#@r{ if we're going to add a digit on the next line}
g
s/\n.*$//
/^9*$/ s/^/0/
@end group

@group
#@r{ separate changing/unchanged digits with an x}
s/.9*$/x&/
@end group

@group
#@r{ keep changing digits in hold space}
h
s/^.*x//
y/0123456789/1234567890/
x
@end group

@group
#@r{ keep unchanged digits in pattern space}
s/x.*$//
@end group

@group
#@r{ compose the new number, remove the new-line implicitly added by G}
G
s/\n//
h
@end group
@end example
@c end---------------------------------------------

@node cat -b
@c @section Numbering non-blank lines
@section 空白行以外に番号を付ける

@c Emulating @code{cat -b} is almost the same as @code{cat -n}---we only
@c have to select which lines are to be numbered and which are not.
@c 
@code{cat -b}のエミュレートは，ほとんど@code{cat -n}と同じです --- 我々
は，番号を付ける行と付けない行を選択する必要があっただけです．

@c The part that is common to this script and the previous one is
@c not commented to show how important it is to comment @code{sed}
@c scripts properly...
@c 
このスクリプトの前回ものとの共通部分には，適切な@code{sed}スクリプトへの
コメントがいかに重要かを表示するコメントを付けていません@enddots{}

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

@group
/^$/ @{
  p
  b
@}
@end group

@group
#@r{ Same as cat -n from now}
x
/^$/ s/^.*$/1/
G
h
s/^/      /
s/^ *\(......\)\n/\1  /p
x
s/\n.*$//
/^9*$/ s/^/0/
s/.9*$/x&/
h
s/^.*x//
y/0123456789/1234567890/
x
s/x.*$//
G
s/\n//
h
@end group
@end example
@c end---------------------------------------------

@node wc -c
@c @section Counting chars
@section 文字を数える

@c This script shows another way to do arithmetic with @code{sed}.
@c In this case we have to add possibly large numbers, so implementing
@c this by successive increments would not be feasible (and possibly
@c even more complicated to contrive than this script...).
@c 
以下のスクリプトは，@code{sed}で算数を行なうもう一つの方法を提示していま
す．この状況では，我々は可能な限り大きな数を追加する必要があるので，これ
を正しく増加するように実装することは不可能でしょう(そして，おそらくこの
スクリプトより計算がより複雑になるでしょう@dots{})．

@c The approach is to map numbers to letters, kind of an abacus
@c implemented with @code{sed}.  @samp{a}s are units, @samp{b}s are
@c tenths and so on: we simply add the number of characters
@c on the current line as units, and then propagate the carry
@c to tenths, hundredths, and so on.
@c 
数字を文字に割り当てるアプローチは，@code{sed}を用いたソロバンの実装の一
種です．@samp{a}は一の位，@samp{b}は十の位などになっています．我々は，一
の位として現在の行に文字の数を単純に追加し，十の位，百の位などに繰り上げ
伝搬させています．

@c As usual, running totals are kept in hold space.
@c 
通常通り，実行時の総数はホールドスペースに保持されます．

@c On the last line, we convert the abacus form back to decimal.
@c For the sake of variety, this is done with a loop rather than
@c with some 80 @code{s} commands@footnote{Some implementations
@c have a limit of 199 commands per script}: first we
@c convert units, removing @samp{a}s from the number; then we
@c rotate letters so that tenths become @samp{a}s, and so on
@c until no more letters remain.
@c 
最後の行で，ソロバンを十進数の形式に戻しています．多様性のため，これは80 
の@code{s}コマンドではなく，ループを用いて行なっています@footnote{実装に
よっては，スクリプトごとのコマンドが199に制限されています．}．最初に一の
位を変換し，@samp{a}を数値から削除します．そして十の位が@samp{a}になるよ
うに文字を回転させ，残っている文字が無くなるまでそれを続けます．

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

@group
#@r{ Add n+1 a's to hold space (+1 is for the new-line)}
s/./a/g
H
x
s/\n/a/
@end group

@group
#@r{ Do the carry.  The t's and b's are not necessary,}
#@r{ but they do speed up the thing}
t a
: a;  s/aaaaaaaaaa/b/g; t b; b done
: b;  s/bbbbbbbbbb/c/g; t c; b done
: c;  s/cccccccccc/d/g; t d; b done
: d;  s/dddddddddd/e/g; t e; b done
: e;  s/eeeeeeeeee/f/g; t f; b done
: f;  s/ffffffffff/g/g; t g; b done
: g;  s/gggggggggg/h/g; t h; b done
: h;  s/hhhhhhhhhh//g
@end group

@group
: done
$! @{
  h
  b
@}
@end group

#@r{ On the last line, convert back to decimal}

@group
: loop
/a/! s/[b-h]*/&0/
s/aaaaaaaaa/9/
s/aaaaaaaa/8/
s/aaaaaaa/7/
s/aaaaaa/6/
s/aaaaa/5/
s/aaaa/4/
s/aaa/3/
s/aa/2/
s/a/1/
@end group

@group
: next
y/bcdefgh/abcdefg/
/[a-h]/ b loop
p
@end group
@end example
@c end---------------------------------------------

@node wc -w
@c @section Counting words
@section 単語を数える

@c This script is almost the same as the previous one, once each
@c of the words on the line is converted to a single @samp{a}
@c (in the previous script each letter was changed to an @samp{a}).
@c 
このスクリプトは，前回のものとほとんど同じで，行にあるそれぞれの単語を単
一の@samp{a}に一度変換します(前回のスクリプトでは，それぞれの文字を
@samp{a}に変更しています)．

@c It is interesting that real @code{wc} programs have optimized
@c loops for @code{wc -c}, so they are much slower at counting
@c words rather than characters.  These scripts' bottleneck,
@c instead, is arithmetic, and hence the word-counting one
@c is faster (it has to manage smaller numbers).
@c 
本物の@code{wc}プログラムは@code{wc -c}に対しループが最適化されているの
で，文字を数えるより単語を数える方がはるかに遅くなります．これらのスクリ
プトのボトルネックは，どちらかというと算数にあり，このため，単語を数える
ものはより速くなります(より小さい数を管理する必要があります)．

@c Again, the common parts are not commented to show the importance
@c of commenting @code{sed} scripts.
@c 
前回同様，共通部分には@code{sed}スクリプトへのコメントの重要性を示すコメ
ントがありません．

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

@group
#@r{ Convert words to a's}
s/[ @kbd{tab}][ @kbd{tab}]*/ /g
s/^/ /
s/ [^ ][^ ]*/a /g
s/ //g
@end group

@group
#@r{ Append them to hold space}
H
x
s/\n//
@end group

@group
#@r{ From here on it is the same as in wc -c.}
/aaaaaaaaaa/! bx;   s/aaaaaaaaaa/b/g
/bbbbbbbbbb/! bx;   s/bbbbbbbbbb/c/g
/cccccccccc/! bx;   s/cccccccccc/d/g
/dddddddddd/! bx;   s/dddddddddd/e/g
/eeeeeeeeee/! bx;   s/eeeeeeeeee/f/g
/ffffffffff/! bx;   s/ffffffffff/g/g
/gggggggggg/! bx;   s/gggggggggg/h/g
s/hhhhhhhhhh//g
:x
$! @{ h; b; @}
:y
/a/! s/[b-h]*/&0/
s/aaaaaaaaa/9/
s/aaaaaaaa/8/
s/aaaaaaa/7/
s/aaaaaa/6/
s/aaaaa/5/
s/aaaa/4/
s/aaa/3/
s/aa/2/
s/a/1/
y/bcdefgh/abcdefg/
/[a-h]/ by
p
@end group
@end example
@c end---------------------------------------------

@node wc -l
@c @section Counting lines
@section 行を数える

@c No strange things are done now, because @code{sed} gives us
@c @code{wc -l} functionality for free!!! Look:
@c 
@code{sed}はに@code{wc -l}の機能があるので，今回はおかしなことを何もしま
せん！！！ まあ見てください．

@c start-------------------------------------------
@example
@group
#!/usr/bin/sed -nf
$=
@end group
@end example
@c end---------------------------------------------

@node head
@c @section Printing the first lines
@section 最初の行を出力する

@c This script is probably the simplest useful @code{sed} script.
@c It displays the first 10 lines of input; the number of displayed
@c lines is right before the @code{q} command.
@c 
以下のスクリプトは，おそらく最も単純で役に立つ@code{sed}スクリプトです．
それは入力の最初の十行を表示します．表示される行の数は，@code{q}コマンド
の前と同じです．

@c start-------------------------------------------
@example
@group
#!/usr/bin/sed -f
10q
@end group
@end example
@c end---------------------------------------------

@node tail
@c @section Printing the last lines
@section 最後の行を出力する

@c Printing the last @var{n} lines rather than the first is more complex
@c but indeed possible.  @var{n} is encoded in the second line, before
@c the bang character.
@c 
最初ではなく最後の@var{n}行出力することはより複雑ですが実現可能です．
@var{n}は，文字を駄目にする前に二行目でエンコードされます．

@c This script is similar to the @code{tac} script in that it keeps the
@c final output in hold space and prints it at the end:
@c 
このスクリプトは，最終的な出力をホールドスペースに保持し，最後に出力する
@code{tac}スクリプトに似ています．

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

@group
1! @{; H; g; @}
1,10 !s/[^\n]*\n//
$p
h
@end group
@end example
@c end---------------------------------------------

@c Mainly, the scripts keeps a window of 10 lines and slides it
@c by adding a line and deleting the oldest (the substitution command
@c on the second line works like a @code{D} command but does not
@c restart the loop).
@c 
そのスクリプトの中心では，10行のウィンドウを保持し，行を追加し最も古い行
を削除しながらスライドしていきます(二行目の置換コマンドは@code{D}コマン
ドのように動作しますがループを再開しません)．

@c The ``sliding window'' technique is a very powerful way to write
@c efficient and complex @code{sed} scripts, because commands like
@c @code{P} would require a lot of work if implemented manually.
@c 
``スライドウィンドウ''のテクニックは，効率的で複雑な@code{sed}を書く強力
な方法で，それは，@code{P}のようなコマンドを手動で実装する場合は多くの作
業が必要になるためです．

@c To introduce the technique, which is fully demonstrated in the
@c rest of this chapter and is based on the @code{N}, @code{P}
@c and @code{D} commands, here is an implementation of @code{tail}
@c using a simple `sliding window'.
@c 
この章の残りで十分に説明している，@code{N}，@code{P}，そして@code{D}コマ
ンドを基本としているテクニックを導入するため，単純な`スライドウィンドウ' 
を使用している@code{tail}の実装を以下に上げます．

@c This looks complicated but in fact the working is the same as
@c the last script: after we have kicked in the appropriate number
@c of lines, however, we stop using hold space to keep inter-line
@c state, and instead use @code{N} and @code{D} to slide pattern
@c space by one line:
@c 
これは複雑に見えますが，実際最後のスクリプトと同じように動作します．しか
し，適切な行数を捨てた後で，内部の行の場所を保持するためのホールドスペー
スを使用するために停止し，パターンスペースを一行スライドするために
@code{N}と@code{D}を代わりに使用しています．

@c start-------------------------------------------
@example
#!/usr/bin/sed -f

@group
1h
2,10 @{; H; g; @}
$q
1,9d
N
D
@end group
@end example
@c end---------------------------------------------


@node uniq
@c @section Make duplicate lines unique
@section 重複した行を一行にする

@c This is an example of the art of using the @code{N}, @code{P}
@c and @code{D} commands, probably the most difficult to master.
@c 
以下は，@code{N}，@code{P}，そして@code{D}コマンドを使用した，おそらくマ
スターするのが最も難しい芸術的な例です．

@c start-------------------------------------------
@example
@group
#!/usr/bin/sed -f
h
@end group

@group
:b
@r{On the last line, print and exit}
$b
N
/^\(.*\)\n\1$/ @{
    # The two lines are identical.  Undo the effect of
    # the n command.
    g
    bb
@}
@end group

@group
#@r{ If the @code{N} command had added the last line, print and exit}
$b
@end group

@group
#@r{ The lines are different; print the first and go}
#@r{ back working on the second.}
P
D
@end group
@end example
@c end---------------------------------------------

@c As you can see, we mantain a 2-line window using @code{P} and @code{D}.
@c This technique is often used in advanced @code{sed} scripts.
@c 
御覧のように，@code{P}と@code{D}を使用して二行のウィンドウを管理していま
す．このテクニックは，高度な@code{sed}スクリプトでよく使用されます．

@node uniq -d
@c @section Print duplicated lines of input
@section 入力の重複している行を出力する．

@c This script prints only duplicated lines, like @code{uniq -d}.
@c 
以下のスクリプトは，@code{uniq -d}のように重複している行だけを出力します．

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

@group
$b
N
/^\(.*\)\n\1$/ @{
    #@r{ Print the first of the duplicated lines}
    s/.*\n//
    p
@end group

@group
    #@r{ Loop until we get a different line}
    :b
    $b
    N
    /^\(.*\)\n\1$/ @{
        s/.*\n//
        bb
    @}
@}
@end group

@group
#@r{ The last line cannot be followed by duplicates}
$b
@end group

@group
#@r{ Found a different one.  Leave it alone in the pattern space}
#@r{ and go back to the top, hunting its duplicates}
D
@end group
@end example
@c end---------------------------------------------

@node uniq -u
@c @section Remove all duplicated lines
@section すべての重複行を削除する

@c This script prints only unique lines, like @code{uniq -u}.
@c 
以下のスクリプトは，@code{uniq -u}のようにユニークな行だけを出力します．

@c start-------------------------------------------
@example
#!/usr/bin/sed -f

@group
#@r{ Search for a duplicate line --- until that, print what you find.}
$b
N
/^\(.*\)\n\1$/ ! @{
    P
    D
@}
@end group

@group
:c
#@r{ Got two equal lines in pattern space.  At the}
#@r{ end of the file we simply exit}
$d
@end group

@group
#@r{ Else, we keep reading lines with @code{N} until we}
#@r{ find a different one}
s/.*\n//
N
/^\(.*\)\n\1$/ @{
    bc
@}
@end group

@group
#@r{ Remove the last instance of the duplicate line}
#@r{ and go back to the top}
D
@end group
@end example
@c end---------------------------------------------

@node cat -s
@c @section Squeezing blank lines
@section 空白行をまとめる

@c As a final example, here are three scripts, of increasing complexity
@c and speed, that implement the same function as @code{cat -s}, that is
@c squeezing blank lines.
@c 
最後の例として，空白行をまとめる@code{cat -s}と同じ機能を実装している，
複雑さと速度を上げていく三つのスクリプトを以下に書きます．

@c The first leaves a blank line at the beginning and end if there are
@c some already.
@c 
最初のものは，最初に空白行を取り去り，まだ残っていれば最後に取り去ります．

@c start-------------------------------------------
@example
#!/usr/bin/sed -f

@group
#@r{ on empty lines, join with next}
#@r{ Note there is a star in the regexp}
:x
/^\n*$/ @{
N
bx
@}
@end group

@group
#@r{ now, squeeze all '\n', this can be also done by:}
#@r{ @code{s/^\(\n\)*/\1/}}
s/\n*/\
/
@end group
@end example
@c end---------------------------------------------

@c This one is a bit more complex and removes all empty lines
@c at the beginning.  It does leave a single blank line at end
@c if one was there.
@c 
以下のものはより複雑で，最初にすべての空の行を取り除きます．まだ残ってい
る場合，最後に単一の空白行を取り去ります．

@c start-------------------------------------------
@example
#!/usr/bin/sed -f

@group
#@r{ delete all leading empty lines}
1,/^./@{
/./!d
@}
@end group

@group
#@r{ on an empty line we remove it and all the following}
#@r{ empty lines, but one}
:x
/./!@{
N
s/^\n$//
tx
@}
@end group
@end example
@c end---------------------------------------------

@c This removes leading and trailing blank lines.  It is also the
@c fastest.  Note that loops are completely done with @code{n} and
@c @code{b}, without exploting the fact that @code{sed} cycles back
@c to the top of the script automatically at the end of a line.
@c 
以下は，前置および後置されている空白行を取り除きます．それは最も速いもの
です．@code{sed}が行の終りで自動的にスクリプトの最初のサイクルに戻るとい
う事実を利用することなく，@code{n}と@code{b}を用いて複雑なループを実行し
ていることに注意してください．

@c start-------------------------------------------
@example
#!/usr/bin/sed -nf

@group
#@r{ delete all (leading) blanks}
/./!d
@end group

@group
#@r{ get here: so there is a non empty}
:x
#@r{ print it}
p
#@r{ get next}
n
#@r{ got chars? print it again, etc... }
/./bx
@end group

@group
#@r{ no, don't have chars: got an empty line}
:z
#@r{ get next, if last line we finish here so no trailing}
#@r{ empty lines are written}
n
#@r{ also empty? then ignore it, and get next... this will}
#@r{ remove ALL empty lines}
/./!bz
@end group

@group
#@r{ all empty lines were deleted/ignored, but we have a non empty.  As}
#@r{ what we want to do is to squeeze, insert a blank line artificially}
i\
@end group

bx
@end example
@c end---------------------------------------------

@node Limitations
@c @chapter @value{SSED}'s limitations and non-limitations
@chapter @value{SSED}の制限と制限されていないこと

@cindex @acronym{GNU} extensions, unlimited line length
@cindex Portability, line length limitations
@c For those who want to write portable @code{sed} scripts,
@c be aware that some implementations have been known to
@c limit line lengths (for the pattern and hold spaces)
@c to be no more than 4000 bytes.
@c The @sc{posix.2} standard specifies that conforming @code{sed}
@c implementations shall support at least 8192 byte line lengths.
@c @value{SSED} has no built-in limit on line length;
@c as long as it can malloc() more (virtual) memory,
@c you can feed or construct lines as long as you care.
@c 
移植性の高い@code{sed}スクリプトを書こうとしている人々は，実装形式によっ
ては，(パターンスペースとホールドスペースの)行の長さに，最大でも4000バイ
トまでという既知の制限が有ることを覚えておいてください．@sc{posix.2}の標
準では，それに準じている@code{sed}の実装を少なくとも8192バイトの行の長さ
をサポートするように指定しています．@value{SSED}には行の長さに組み込まれ
ている制限はありません．(仮想)メモリ上でmalloc()することが可能な限り，心
配するほど長い行を，与えたり構成したりすることが可能です．

@c However, recursion is used to handle subpatterns and indefinite
@c repetition.  This means that the available stack space may limit
@c the size of the buffer that can be processed by certain patterns.
@c 
しかし，再帰はサブパターンの処理と不定の反復で使用されます．これで，利用
可能なスタックスペースは，特定のパターンで処理されるバッファのサイズを制
限するかもしれません．

@ifset PERL
@c not-translate
There are some size limitations in the regular expression
matcher but it is hoped that they will never in practice
be relevant.  The maximum length of a compiled pattern
is 65539 (sic) bytes.  All values in repeating quantifiers
must be less than 65536.  The maximum nesting depth of
all parenthesized subpatterns, including capturing and
non-capturing subpatterns@footnote{The
distinction is meaningful when referring to Perl-style
regular expressions.}, assertions, and other types of
subpattern, is 200.

Also, @value{SSED} recognizes the @sc{posix} syntax
@code{[.@var{ch}.]} and @code{[=@var{ch}=]}
where @var{ch} is a ``collating element'', but these
are not supported, and an error is given if they are
encountered.

Here are a few distinctions between the real Perl-style
regular expressions and those that @code{-R} recognizes.

@enumerate
@item
Lookahead assertions do not allow repeat quantifiers after them
Perl permits them, but they do not mean what you
might think. For example, @samp{(?!a)@{3@}} does not assert that the
next three characters are not @samp{a}. It just asserts three times that the
next character is not @samp{a} --- a waste of time and nothing else.

@item
Capturing subpatterns that occur inside  negative  lookahead
head  assertions  are  counted,  but  their  entries are counted
as empty in the second half of an @code{s} command.
Perl sets its numerical variables from any such patterns
that are matched before the assertion fails to match
something (thereby succeeding), but only if the negative
lookahead assertion contains just one branch.

@item
The following Perl escape sequences are not supported:
@samp{\l}, @samp{\u}, @samp{\L}, @samp{\U}, @samp{\E},
@samp{\Q}. In fact these are implemented by Perl's general
string-handling and are not part of its pattern matching engine.

@item
The Perl @samp{\G} assertion is not supported as it is not
relevant to single pattern matches.

@item
Fairly obviously, @value{SSED} does not support the @samp{(?@{code@})}
and @samp{(?p@{code@})} constructions. However, there is some experimental
support for recursive patterns using the non-Perl item @samp{(?R)}.

@item
There are at the time of writing some oddities in Perl
5.005_02 concerned with the settings of captured strings
when part of a pattern is repeated. For example, matching
@samp{aba} against the pattern @samp{/^(a(b)?)+$/} sets
@samp{$2}@footnote{@samp{$2} would be @samp{\2} in @value{SSED}.}
to the value @samp{b}, but matching @samp{aabbaa}
against @samp{/^(aa(bb)?)+$/} leaves @samp{$2}
unset.  However, if the pattern is changed to
@samp{/^(aa(b(b))?)+$/} then @samp{$2} (and @samp{$3}) are set.
In Perl 5.004 @samp{$2} is set in both cases, and that is also
true of @value{SSED}.

@item
Another as yet unresolved discrepancy is that in Perl
5.005_02 the pattern @samp{/^(a)?(?(1)a|b)+$/} matches
the string @samp{a}, whereas in @value{SSED} it does not.
However, in both Perl and @value{SSED} @samp{/^(a)?a/} matched
against @samp{a} leaves $1 unset.
@end enumerate
@end ifset

@node Other Resources
@c @chapter Other resources for learning about @code{sed}
@chapter @code{sed}を学ぶ際のその他の情報源

@cindex Additional reading about @code{sed}
@c In addition to several books that have been written about @code{sed}
@c (either specifically or as chapters in books which discuss
@c shell programming), one can find out more about @code{sed}
@c (including suggestions of a few books) from the FAQ
@c for the sed-users mailing list, available from any of:
@c 
@code{sed}に関して書かれているいくつかの本(または，シェルプログラミング
について論じている本の特定の章)に加えて，@code{sed}について(数冊の本の示
唆を含めて)以下で利用可能な@code{sed}ユーザのメーリングリストのFAQで見つ
けることが可能です．
@display
 @uref{http://www.student.northpark.edu/pemente/sed/sedfaq.html}
 @uref{http://sed.sf.net/grabbag/tutorials/sedfaq.html}
@end display

@c Also of interest are
@c @uref{http://www.student.northpark.edu/pemente/sed/index.htm}
@c and @uref{http://sed.sf.net/grabbag},
@c which include sed tutorials and other sed-related goodies.
@c 
また興味あるものとして，@code{sed}のチュートリアルとその他の@code{sed}関
連グッズが含まれているものは，
@uref{http://www.student.northpark.edu/pemente/sed/index.htm}と
@uref{http://sed.sf.net/grabbag}です．

@c There is a ``sed-users'' mailing list maintained by Sven Guckes.
@c To subscribe, visit @uref{http://groups.yahoo.com} and search
@c for the @code{sed-users} mailing list.
@c 
Sven Guckesが管理している非公式の``sed-users''のメーリングリストがありま
す．購読するためには，@uref{http://groups.yahoo.com}を訪問し，
@code{sed-users}メーリングリストを検索してください．

@node Reporting Bugs
@c @chapter Reporting bugs
@chapter バグの報告

@cindex Bugs, reporting
@c Email bug reports to @email{bonzini@@gnu.org}.
@c Be sure to include the word ``sed'' somewhere in the @code{Subject:} field.
@c Also, please include the output of @code{sed --version} in the body
@c of your report if at all possible.
@c 
バグの報告は@email{bug-gnu-utils@@gnu.org}に電子メールを送ってください．
@code{Subject:}フィールドのどこかに，単語``sed''を含めてください．また，
可能であれば，報告の内容に@code{sed --version}の出力も含めてください．

@c Please do not send a bug report like this:
@c 
以下のようなバグの報告を送らないでください．

@example
	@r{[while building frobme-1.3.4]}
	$ configure 
	sed: file sedscr line 1: Unknown option to 's'
@end example

@c If @value{SSED} doesn't configure your favorite package, take a
@c few extra minutes to identify the specific problem and make a stand-alone
@c test case.  Unlike other programs such as C compilers, making such test
@c cases for @code{sed} is quite simple.
@c 
@value{SSED}でお気に入りのパッケージをコンフィグレーションできない場合，
特定の問題を確認するために時間をかけ，スタンドアローンのテストケースを作
成してください．Cコンパイラのようなその他のプログラムとは異なり，
@code{sed}に対してそのようなテストケースを作成することはまったく単純です．

@c A stand-alone test case includes all the data necessary to perform the
@c test, and the specific invocation of @code{sed} that causes the problem.
@c The smaller a stand-alone test case is, the better.  A test case should
@c not involve something as far removed from @code{sed} as ``try to configure
@c frobme-1.3.4''.  Yes, that is in principle enough information to look
@c for the bug, but that is not a very practical prospect.
@c 
スタンドアローンのテストケースには，テストを実行するために必要なすべての
データと，問題を生じた@code{sed}の呼び出しで指定したものを含めてください．
スタンドアローンのテストケースは小さい方が良いでしょう．テストケースは，
``frobme-1.3.4のコンフィグレーションを試みた''というような，@code{sed} 
からかけ離れているものを必要とすべきではありません．そうです，それはバグ
を探す情報として原則的には十分ですが，見通しはあまり現実的ではありません．

@c Here are a few commonly reported bugs that are not bugs.
@c 
以下は一般的なバグやバグではないもので報告されているものです．

@table @asis
@c @item @code{sed -n} and @code{s/regex/replace/p}
@item @code{sed -n}と@code{s/regex/replace/p}
@cindex Portability, @code{p} command and @samp{-n} flag
@cindex Non-bugs, @code{p} command and @samp{-n} flag
@c Some versions of sed ignore the `p' (print) option of an `s' command
@c unless the `-n' command switch has been specified.  Other versions
@c always honor the `p' option.  Both approaches are allowed by @sc{posix.2}
@c and @sc{gnu} @code{sed} (on which @value{SSED} is based) is the
@c latter sort; I judge this approach to be better (give enough rope
@c etc.) when you write complex scripts, but portable scripts should
@c be written to work correctly with either behavior.
@c 
@code{sed}のバージョンによっては，`-n'コマンドスイッチが指定されていない
限り`s'コマンドの`p'(プリント)オプションを無視するものがあります．それ以
外のバージョンは`p'オプションを尊重します．どちらの手法も@sc{posix.2}で
は許可されていて，@sc{gnu} @code{sed}(@value{SSED}を基本としたもの)では
後者の手法になっています．私は，複雑なスクリプトを書くときは，この手法が
より良いと思っています(自由に行動できます)が，移植性の高いスクリプトでは，
どちらの動作でも正しく動作するように書くべきです．

@c @item regex syntax clashes
@item 正規表現の構文の破壊
@cindex @acronym{GNU} extensions, to basic regular expressions
@cindex Non-bugs, regex syntax clashes
@c @code{sed} uses the Posix basic regular expression syntax.  According to
@c the standard, the meaning of some escape sequences is undefined in
@c this syntax;  notable in the case of @code{sed} are @code{\|},
@c @code{\+}, @code{\?}, @code{\@code{}, @code{\}}, @code{\<},
@c @code{\>}, @code{\b}, @code{\B}, @code{\w}, and @code{\W}.
@c 
@code{sed}は，Posixの基本正規表現の構文を使用しています．標準によると，
エスケープシーケンスの意味はこの構文では未定義です．@code{sed}で有名なも
のは，@code{\|}，@code{\+}，@code{\?}，@code{\@code{}，@code{\}}，
@code{\<}，@code{\>}，@code{\b}，@code{\B}，@code{\w}，そして@code{\W}で
す．

@c As in all GNU programs that use Posix basic regular expressions, sed
@c interprets these escape sequences as meta-characters.  So, @code{x\+}
@c matches one or more occurrences of @code{x}.  @code{abc\|def} matches
@c either @code{abc} or @code{def}.
@c 
Posixの基本正規表現を使用しているすべてのGNUプログラムでは，@code{sed}は
これらのエスケープシーケンスをメタ文字として解釈します．そのため，
@code{x\+}は一つ以上の@code{x}の出現にマッチします．@code{abc\|def}は
@code{abc}または@code{def}にマッチします．

@c This syntax may cause problems when running scripts written for other
@c @code{sed}s.  Some @code{sed} programs have been written with the
@c assumption that @code{\|} and @code{\+} match the literal characters
@c @code{|} and @code{+}.  Such scripts must be modified by removing the
@c spurious backslashes if they are to be used with modern implementations
@c of @code{sed}, like @sc{gnu} @code{sed} or @value{SSED}.
@c 
この構文は，他の@code{sed}に対して書かれたスクリプトを実行するとき問題に
なるかもしれません．@code{sed}プログラムには，@code{\|}と@code{\+}がリテ
ラル文字の@code{|}と@code{+}にマッチするという仮定を用いて書かれているも
のもあります．そのようなスクリプトを，@sc{gnu} @code{sed}や@value{SSED} 
のような近代的な@code{sed}を実装しているものを用いて使用する場合，贋のバッ
クスラッシュを削除して修正する必要があります．

@cindex @acronym{GNU} extensions, special escapes
@c In addition, this version of @code{sed} supports several escape characters
@c (some of which are multi-character) to insert non-printable characters
@c in scripts (@code{\a}, @code{\c}, @code{\d}, @code{\o}, @code{\r},
@c @code{\t}, @code{\v}, @code{\x}).  These can cause similar problems
@c with scripts written for other @code{sed}s.
@c 
更に，このバージョンの@code{sed}は，印刷不可能な文字(マルチバイト文字を
含む)をスクリプトに挿入するため，いくつかのエスケープ文字(@code{\a}，
@code{\c}，@code{\d}，@code{\o}，@code{\r}，@code{\t}，@code{\v}，
@code{\x})をサポートしています．これらは，他の@code{sed}に対して書かれて
いるスクリプトで同様な問題を生じるでしょう．

@c @item @code{-i} clobbers read-only files
@item @code{-i}で読み込み専用のファイルを破壊する
@cindex In-place editing
@cindex @value{SSEDEXT}, in-place editing
@cindex Non-bugs, in-place editing

@c In short, @code{sed d -i} will let one delete the contents of
@c a read-only file, and in general the @code{-i} option
@c (@pxref{Invoking sed, , Invocation} will let one clobber
@c protected files.  This is not a bug, but rather a consequence
@c of how the Unix filesystem works.
@c 
手短に言うと，@code{sed d -i}では読み取り専用のファイルの内容を削除し，
一般的に@code{-i}オプション((@pxref{Invoking sed, , Invocation})では保護
されたファイルを破壊します．これはバグではありませんが，Unixファイルシス
テムで動作する方法に影響します．

@c The permissions on a file say what can happen to the data
@c in that file, while the permissions on a directory say what can
@c happen to the list of files in that directory.  @code{sed -i}
@c will not ever open for writing  a file that is already on disk,
@c rather, it will work on a temporary file that is finally renamed
@c to the original name: if you rename or delete files, you're actually
@c modifying the contents of the directory, so the operation depends on
@c the permissions of the directory, not of the file).  For this same
@c reason, @code{sed} will not let one use @code{-i} on a writeable file
@c in a read-only directory (but unbelievably nobody reports that as a
@c bug@dots{}).
@c 
ファイルへの許可はファイルのデータに生じる可能性があることを告げています
が，ディレクトリの許可はディレクトリのファイルのリストに生じる可能性があ
ることを告げています．@code{sed -i}は書き込み属性でディスクに存在してい
るファイルを開きませんが，最終的にはオリジナルファイル名に名前を変更する
一時的なファイルで作業します．ファイルの名前を変更したり削除したりする場
合，実際にはディレクトリの内容を編集していることになるので，その処理はファ
イルではなくディレクトリの許可に依存します．同じ理由で，@code{sed}は読み
込み専用のディレクトリの書き込み可能なファイルで@code{-i}を使用しません
(しかし，信じられないことにバグとして報告してきた人はいません@dots{})．

@end table

@node Extended regexps
@c @appendix Extended regular expressions
@appendix 拡張正規表現
@cindex Extended regular expressions, syntax

@c The only difference between basic and extended regular expressions is in
@c the behavior of a few characters: @samp{?}, @samp{+}, parentheses,
@c and braces (@samp{@{@}}).  While basic regular expressions require
@c these to be escaped if you want them to behave as special characters,
@c when using extended regular expressions you must escape them if
@c you want them @emph{to match a literal character}.
@c 
正規表現の基本と拡張の差は，いくつかの文字の動作だけです．それは@samp{?}，
@samp{+}，丸カッコ，そして弓カッコ(@samp{@{@}})です．基本正規表現では，
それらを特殊文字として動作させたい場合，これらをエスケープする必要があり
ますが，拡張正規表現を使用しているとき，@emph{文字そのものにマッチさせた
い場合}エスケープする必要があります．

@noindent
@c Examples:
@c 
例えば以下のようになります．
@table @samp
@item abc?
@c becomes @samp{abc\?} when using extended regular expressions.  It matches
@c the literal string @samp{abc?}.
@c 
拡張正規表現を使用しているとき@samp{abc\?}になります．それは文字列
@samp{abc?}そのものにマッチします．

@item c\+
@c becomes @samp{c+} when using extended regular expressions.  It matches
@c one or more @samp{c}s.
@c 
拡張正規表現を使用しているとき@samp{c+}になります．それは一つ以上の
@samp{c}にマッチします．

@item a\@{3,\@}
@c becomes @samp{a@{3,@}} when using extended regular expressions.  It matches
@c three or more @samp{a}s.
@c 
拡張正規表現を使用しているとき@samp{a@{3,@}}になります．それは三つ以上の
@samp{a}にマッチします．

@item \(abc\)\@{2,3\@}
@c becomes @samp{(abc)@{2,3@}} when using extended regular expressions.  It
@c matches either @samp{abcabc} or @samp{abcabcabc}.
@c 
拡張正規表現を使用しているとき@samp{(abc)@{2,3@}}になります．それは
@samp{abcabc}または@samp{abcabcabc}のいずれかにマッチします．

@item \(abc*\)\1
@c becomes @samp{(abc*)\1} when using extended regular expressions.
@c Backreferences must still be escaped when using extended regular
@c expressions.
@c 
拡張正規表現を使用しているとき@samp{(abc*)\1}になります．後方参照は拡張
正規表現を使用しているときもエスケープする必要があります．
@end table

@ifset PERL
@c not-translate
@node Perl regexps
@appendix Perl-style regular expressions
@cindex Perl-style regular expressions, syntax

@emph{This part is taken from the @code{pcre.txt} file distributed together with the free @sc{pcre} regular expression matcher; it was written by Philip Hazel.}

Perl introduced several extensions to regular expressions, some
of them incompatible with the syntax of regular expressions
accepted by Emacs and other @sc{gnu} tools (whose matcher was
based on the Emacs matcher).  @value{SSED} implements
both kinds of extensions.

@iftex
Summarizing, we have:

@itemize @bullet
@item
A backslash can introduce several special sequences

@item
The caret, dollar, and full stop characters behave specially 
with regard to new lines

@item
Strange uses of square brackets are parsed differently

@item
You can toggle modifiers in the middle of a regular expression

@item
You can specify that a subpattern does not count when numbering backreferences

@item
@cindex Greedy regular expression matching
You can specify greedy or non-greedy matching

@item
You can have more than ten back references

@item
You can do complex look aheads and look behinds (in the spirit of
@code{\b}, but with subpatterns).

@item
You can often improve performance by avoiding that @code{sed} wastes
time with backtracking

@item
You can have if/then/else branches

@item
You can do recursive matches, for example to look for unbalanced parentheses

@item
You can have comments and non-significant whitespace, because things can
get complex...
@end itemize

Most of these extensions are introduced by the special @code{(?}
sequence, which gives special meanings to parenthesized groups.
@end iftex
@menu
Other extensions can be roughly subdivided in two categories
On one hand Perl introduces several more escaped sequences
(that is, sequences introduced by a backslash).  On the other
hand, it specifies that if a question mark follows an open
parentheses it should give a special meaning to the parenthesized
group.

* Backslash::                       Introduces special sequences
* Caret/dollar/full stop::          Behave specially with regard to new lines
* Square brackets::                 Are a bit different in strange cases
* Options setting::                 Toggle modifiers in the middle of a regexp
* Non-capturing subpatterns::       Are not counted when backreferencing
* Repetition::                      Allows for non-greedy matching
* Backreferences::                  Allows for more than 10 back references
* Assertions::                      Allows for complex look ahead matches
* Non-backtracking subpatterns::    Often gives more performance
* Conditional subpatterns::         Allows if/then/else branches
* Recursive patterns::              For example to match parentheses
* Comments::                        Because things can get complex...
@end menu

@node Backslash
@appendixsec Backslash
@cindex Perl-style regular expressions, escaped sequences

There are a few difference in the handling of backslashed 
sequences in Perl mode.

First of all, there are no @code{\o} and @code{\d} sequences.
@sc{ascii} values for characters can be specified in octal
with a @code{\@var{xxx}} sequence, where @var{xxx} is a
sequence of up to three octal digits.  If the first digit
is a zero, the treatment of the sequence is straightforward;
just note that if the character that follows the escaped digit
is itself an octal digit, you have to supply three octal digits
for @var{xxx}.  For example @code{\07} is a @sc{bel} character
rather than a @sc{nul} and a literal @code{7} (this sequence is
instead represented by @code{\0007}).

@cindex Perl-style regular expressions, backreferences
The handling of a backslash followed by a digit other than 0
is complicated.  Outside a character class, @code{sed} reads it
and any following digits as a decimal number. If the number
is less than 10, or if there have been at least that many
previous capturing left parentheses in the expression, the
entire sequence is taken as a back reference. A description
of how this works is given later, following the discussion
of parenthesized subpatterns.

Inside a character class, or if the decimal number is
greater than 9 and there have not been that many capturing
subpatterns, @code{sed} re-reads up to three octal digits following
the backslash, and generates a single byte from the
least significant 8 bits of the value. Any subsequent digits
stand for themselves.  For example:

@example
     \040  @r{is another way of writing a space}
     \40   @r{is the same, provided there are fewer than 40}
           @r{previous capturing subpatterns}
     \7    @r{is always a back reference}
     \011  @r{is always a tab}
     \11   @r{might be a back reference, or another way of}
           @r{writing a tab}
     \0113 @r{is a tab followed by the character @samp{3}}
     \113  @r{is the character with octal code 113 (since there}
           @r{can be no more than 99 back references)}
     \377  @r{is a byte consisting entirely of 1 bits (@sc{ascii} 255)}
     \81   @r{is either a back reference, or a binary zero}
           @r{followed by the two characters @samp{81}}
@end example

Note that octal values of 100 or greater must not be introduced
duced by a leading zero, because no more than three octal
digits are ever read.

All the sequences that define a single byte value can be
used both inside and outside character classes. In addition,
inside a character class, the sequence @code{\b} is interpreted
as the backspace character (hex 08). Outside a character
class it has a different meaning (see below).

In addition, there are two additional escapes specifying
generic character classes (like @code{\s}, @code{\S}, @code{\w}
and @code{\W} do):

@cindex Perl-style regular expressions, character classes
@table @samp
@item \d
Matches any decimal digit

@item \D
Matches any character that is not a decimal digit
@end table

In Perl mode, these character type sequences can appear both inside and
outside character classes. Instead, in @sc{posix} mode these sequences
(as well as @code{\s}, @code{\S}, @code{\w}, @code{\W}) are treated
as two literal characters (a backslash and a letter) inside square
brackets.

Escaped sequences specifying assertions are also different in
Perl mode.  An assertion specifies a condition that has to be met
at a particular point in a match, without consuming any
characters from the subject string. The use of subpatterns
for more complicated assertions is described below.  The
backslashed assertions are

@cindex Perl-style regular expressions, assertions
@table @samp
@item \b
Asserts that the point is at a word boundary.
A word boundary is a position in the subject string where
the current character and the previous character do not both
match @code{\w} or @code{\W} (i.e. one matches @code{\w} and
the other matches @code{\W}), or the start or end of the string
if the first or last character matches @code{\w}, respectively.

@item \B
Asserts that the point is not at a word boundary.

@item \A
Asserts the matcher is at the start of pattern space (independent
of multiline mode).

@item \Z
Asserts the matcher is at the end of pattern space,
or at a newline before the end of pattern space (independent of
multiline mode)

@item \z
Asserts the matcher is at the end of pattern space (independent
of multiline mode)
@end table

These assertions may not appear in character classes (but
note that @code{\b} has a different meaning, namely the
backspace character, inside a character class).
Note that Perl mode does not support directly assertions
for the beginning and the end of word; the @sc{gnu} extensions
@code{\<} and @code{\>} achieve this purpose in @sc{posix} mode
instead.

The @code{\A}, @code{\Z}, and @code{\z} assertions differ
from the traditional circumflex and dollar (described below)
in that they only ever match at the very start and end of the
subject string, whatever options are set; in particular @code{\A}
and @code{\z} are the same as the @sc{gnu} extensions
@code{\`} and @code{\'} that are active in @sc{posix} mode.

@node Caret/dollar/full stop
@appendixsec Caret, dollar, full stop
@cindex Perl-style regular expressions, new-lines

Outside a character class, in the default matching mode, the
caret character is an assertion which is true only if
the current matching point is at the start of the subject
string.  Inside a character class, the caret has an entirely
different meaning (see below).

The caret need not be the first character of the pattern if
a number of alternatives are involved, but it should be the
first thing in each alternative in which it appears if the
pattern is ever to match that branch. If all possible alternatives,
start with a caret, that is, if the pattern is
constrained to match only at the start of the subject, it is
said to be an @dfn{anchored} pattern. (There are also other constructs
structs that can cause a pattern to be anchored.)

A dollar character is an assertion which is true only if the
current matching point is at the end of the subject string,
or immediately before a newline character that is the last
character in the string (by default). Dollar need not be the
last character of the pattern if a number of alternatives
are involved, but it should be the last item in any branch
in which it appears.  Dollar has no special meaning in a
character class.

@cindex Perl-style regular expressions, multiline
The meanings of the caret and dollar characters are
changed if the @code{M} modifier option is used. When this is
the case, they match immediately after and immediately
before an internal @code{\n} character, respectively, in addition
to matching at the start and end of the subject string.  For
example, the pattern @code{/^abc$/} matches the subject string
@samp{def\nabc} in multiline mode, but not otherwise.  Consequently,
patterns that are anchored in single line mode
because all branches start with @code{^} are not anchored in
multiline mode.

@cindex Perl-style regular expressions, multiline
Note that the sequences @code{\A}, @code{\Z}, and @code{\z}
can be used to match the start and end of the subject in both
modes, and if all branches of a pattern start with @code{\A}
is it always anchored, whether the @code{M} modifier is set or not.

@cindex Perl-style regular expressions, single line
Outside a character class, a dot in the pattern matches any
one character in the subject, including a non-printing character,
but not (by default) newline.  If the @code{S} modifier is used,
dots match newlines as well.  Actually, the handling of
dot is entirely independent of the handling of caret
and dollar, the only relationship being that they both
involve newline characters. Dot has no special meaning in a
character class.

@node Square brackets
@appendixsec Square brackets
@cindex Perl-style regular expressions, character classes

An opening square bracket introduces a character class, terminated
by a closing square bracket.  A closing square bracket on its own
is not special.  If a closing square bracket is required as a
member of the class, it should be the first data character in
the class (after an initial caret, if present) or escaped with a backslash.

A character class matches a single character in the subject;
the character must be in the set of characters defined by
the class, unless the first character in the class is a caret,
in which case the subject character must not be in
the set defined by the class. If a circumflex is actually
required as a member of the class, ensure it is not the
first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower
case vowel, while [^aeiou] matches any character that is not
a lower case vowel. Note that a caret is just a convenient
venient notation for specifying the characters which are in
the class by enumerating those that are not. It is not an
assertion: it still consumes a character from the subject
string, and fails if the current pointer is at the end of
the string.

@cindex Perl-style regular expressions, case-insensitive
When caseless matching is set, any letters in a class
represent both their upper case and lower case versions, so
for example, a caseless @code{[aeiou]} matches uppercase
and lowercase @samp{A}s, and a caseless @code{[^aeiou]}
does not match @samp{A}, whereas a case-sensitive version would.

@cindex Perl-style regular expressions, single line
@cindex Perl-style regular expressions, multiline
The newline character is never treated in any special way in
character classes, whatever the setting of the @code{S} and
@code{M} options (modifiers) is.  A class such as @code{[^a]} will
always match a newline.

The minus (hyphen) character can be used to specify a range
of characters in a character class.  For example, @code{[d-m]}
matches any letter between d and m, inclusive.  If a minus
character is required in a class, it must be escaped with a
backslash or appear in a position where it cannot be interpreted
as indicating a range, typically as the first or last
character in the class.

It is not possible to have the literal character @code{]} as the
end character of a range.  A pattern such as @code{[W-]46]} is
interpreted as a class of two characters (@code{W} and @code{-})
followed by a literal string @code{46]}, so it would match
@samp{W46]} or @samp{-46]}. However, if the @code{]} is escaped
with a backslash it is interpreted as the end of range, so
@code{[W-\]46]} is interpreted as a single class containing a
range followed by two separate characters. The octal or
hexadecimal representation of @code{]} can also be used to end a range.

Ranges operate in @sc{ascii} collating sequence. They can also be
used for characters specified numerically, for example
@code{[\000-\037]}. If a range that includes letters is used when
caseless matching is set, it matches the letters in either
case. For example, a caseless @code{[W-c]} is equivalent to
@code{[][\^_`wxyzabc]}, matched caselessly, and if character
tables for the French locale are in use, @code{[\xc8-\xcb]}
matches accented E characters in both cases.

Unlike in @sc{posix} mode, the character types @code{\d},
@code{\D}, @code{\s}, @code{\S}, @code{\w}, and @code{\W}
may also appear in a character class, and add the characters
that they match to the class. For example, @code{[\dABCDEF]} matches any
hexadecimal digit.  A circumflex can conveniently be used
with the upper case character types to specify a more restricted
set of characters than the matching lower case type.
For example, the class @code{[^\W_]} matches any letter or digit,
but not underscore.

All non-alphameric characters other than @code{\}, @code{-},
@code{^} (at the start) and the terminating @code{]}
are non-special in character classes, but it does no harm
if they are escaped.

Perl 5.6 (not yet released at the time of writing) is going
to support the @sc{posix} notation for character classes, which
uses names enclosed by @code{[:} and @code{:]} within the enclosing
square brackets. @value{SSED} supports this notation.
For example,

@example
     [01[:alpha:]%]
@end example

@noindent
matches @samp{0}, @samp{1}, any alphabetic character, or @samp{%}.
The supported class names are

@table @code
@item alnum
Matches letters and digits

@item alpha
Matches letters

@item ascii
Matches character codes 0 - 127

@item cntrl
Matches control characters

@item digit
Matches decimal digits (same as \d)

@item graph
Matches printing characters, excluding space

@item lower
Matches lower case letters

@item print
Matches printing characters, including space

@item punct
Matches printing characters, excluding letters and digits

@item space
Matches white space (same as \s)

@item upper
Matches upper case letters

@item word
Matches ``word'' characters (same as \w)

@item xdigit
Matches hexadecimal digits
@end table

The names @code{ascii} and @code{word} are extensions valid only in
Perl mode.  Another Perl extension is negation, which is
indicated by a caret character after the colon. For example,

@example
     [12[:^digit:]]
@end example

@noindent
matches @samp{1}, @samp{2}, or any non-digit.

@node Options setting
@appendixsec Options setting
@cindex Perl-style regular expressions, toggling options
@cindex Perl-style regular expressions, case-insensitive
@cindex Perl-style regular expressions, multiline
@cindex Perl-style regular expressions, single line
@cindex Perl-style regular expressions, extended

The settings of the @code{I}, @code{M}, @code{S}, @code{X}
modifiers can be changed from within the pattern by
a sequence of Perl option letters enclosed between @code{(?}
and @code{)}. The option letters must be lowercase.

For example, @code{(?im)} sets caseless, multiline matching. It is
also possible to unset these options by preceding the letter
with a hyphen; you can also have combined settings and unsettings:
@code{(?im-sx)} sets caseless and multiline matching,
while unsets single line matching (for dots) and extended
whitespace interpretation.  If a letter appears both before
and after the hyphen, the option is unset.

The scope of these option changes depends on where in the
pattern the setting occurs. For settings that are outside
any subpattern (defined below), the effect is the same as if
the options were set or unset at the start of matching. The
following patterns all behave in exactly the same way:

@example
     (?i)abc
     a(?i)bc
     ab(?i)c
     abc(?i)
@end example

which in turn is the same as specifying the pattern abc with
the @code{I} modifier.  In other words, ``top level'' settings
apply to the whole pattern (unless there are other
changes inside subpatterns). If there is more than one setting
of the same option at top level, the rightmost setting
is used.

If an option change occurs inside a subpattern, the effect
is different.  This is a change of behaviour in Perl 5.005.
An option change inside a subpattern affects only that part
of the subpattern @emph{that follows} it, so

@example
     (a(?i)b)c
@end example

@noindent
matches abc and aBc and no other  strings  (assuming
case-sensitive matching is used).  By this means, options can
be made to have different settings in different parts of the
pattern.  Any changes made in one alternative do carry on
into subsequent branches within the same subpattern.  For
example,

@example
     (a(?i)b|c)
@end example

@noindent
matches @samp{ab}, @samp{aB}, @samp{c}, and @samp{C},
even though when matching @samp{C} the first branch is
abandoned before the option setting.
This is because the effects of option settings happen at
compile time. There would be some very weird behaviour otherwise.

@ignore
There are two PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA
that can be changed in the same way as the Perl-compatible options by
using the characters U and X respectively.  The (?X) flag
setting is special in that it must always occur earlier in
the pattern than any of the additional features it turns on,
even when it is at top level. It is best put at the start.
@end ignore


@node Non-capturing subpatterns
@appendixsec Non-capturing subpatterns
@cindex Perl-style regular expressions, non-capturing subpatterns

Marking part of a pattern as a subpattern does two things.
On one hand, it localizes a set of alternatives; on the other
hand, it sets up the subpattern as a capturing subpattern (as
defined above).  The subpattern can be backreferenced and
referenced in the right side of @code{s} commands.

For example, if the string @samp{the red king} is matched against
the pattern

@example
     the ((red|white) (king|queen))
@end example

@noindent
the captured substrings are @samp{red king}, @samp{red},
and @samp{king}, and are numbered 1, 2, and 3.

The fact that plain parentheses fulfil two functions is not
always helpful.  There are often times when a grouping
subpattern is required without a capturing requirement.  If an
opening parenthesis is followed by @code{?:}, the subpattern does
not do any capturing, and is not counted when computing the
number of any subsequent capturing subpatterns. For example,
if the string @samp{the white queen} is matched against the pattern

@example
     the ((?:red|white) (king|queen))
@end example

@noindent
the captured substrings are @samp{white queen} and @samp{queen},
and are numbered 1 and 2. The maximum number of captured
substrings is 99, while the maximum number of all subpatterns,
both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are
equired at the start of a non-capturing subpattern, the
option letters may appear between the @code{?} and the
@code{:}.  Thus the two patterns

@example
   (?i:saturday|sunday)
   (?:(?i)saturday|sunday)
@end example

@noindent
match exactly the same set of strings.  Because alternative
branches are tried from left to right, and options are not
reset until the end of the subpattern is reached, an option
setting in one branch does affect subsequent branches, so
the above patterns match @samp{SUNDAY} as well as @samp{Saturday}.


@node Repetition
@appendixsec Repetition
@cindex Perl-style regular expressions, repetitions

Repetition is specified by quantifiers, which can follow any
of the following items:

@itemize @bullet
@item
a single character, possibly escaped

@item
the @code{.} metacharacter

@item
a character class

@item
a back reference (see next section)

@item
a parenthesized subpattern (unless it is an assertion; @pxref{Assertions})
@end itemize

The general repetition quantifier specifies a minimum and
maximum number of permitted matches, by giving the two
numbers in curly brackets (braces), separated by a comma.
The numbers must be less than 65536, and the first must be
less than or equal to the second. For example:

@example
     z@{2,4@}
@end example

@noindent
matches @samp{zz}, @samp{zzz}, or @samp{zzzz}. A closing brace on its own
is not a special character. If the second number is omitted,
but the comma is present, there is no upper limit; if the
second number and the comma are both omitted, the quantifier
specifies an exact number of required matches. Thus

@example
     [aeiou]@{3,@}
@end example

@noindent
matches at least 3 successive vowels, but may match many
more, while

@example
     \d@{8@}
@end example

@noindent
matches exactly 8 digits.  An opening curly bracket that
appears in a position where a quantifier is not allowed, or
one that does not match the syntax of a quantifier, is taken
as a literal character. For example, @{,6@} is not a quantifier,
but a literal string of four characters.@footnote{It
raises an error if @code{-R} is not used.}

The quantifier @{0@} is permitted, causing the expression to
behave as if the previous item and the quantifier were not
present.

For convenience (and historical compatibility) the three
most common quantifiers have single-character abbreviations:

@table @code
@item *
is equivalent to @{0,@}

@item +
is equivalent to @{1,@}

@item ?
is equivalent to @{0,1@}
@end table

It is possible to construct infinite loops by following a
subpattern that can match no characters with a quantifier
that has no upper limit, for example:

@example
     (a?)*
@end example

Earlier versions of Perl used to give an error at
compile time for such patterns. However, because there are
cases where this can be useful, such patterns are now
accepted, but if any repetition of the subpattern does in
fact match no characters, the loop is forcibly broken.

@cindex Greedy regular expression matching
@cindex Perl-style regular expressions, stingy repetitions
By default, the quantifiers are @dfn{greedy} like in @sc{posix}
mode, that is, they match as much as possible (up to the maximum
number of permitted times), without causing the rest of the
pattern to fail. The classic example of where this gives problems
is in trying to match comments in C programs. These appear between
the sequences @code{/*} and @code{*/} and within the sequence, individual
@code{*} and @code{/} characters may appear. An attempt to match C
comments by applying the pattern

@example
     /\*.*\*/
@end example

@noindent
to the string

@example
     /* first command */ not comment /* second comment */
@end example

@noindent

fails, because it matches the entire string owing to the
greediness of the @code{.*} item.

However, if a quantifier is followed by a question mark, it
ceases to be greedy, and instead matches the minimum number
of times possible, so the pattern @code{/\*.*?\*/}
does the right thing with the C comments. The meaning of the
various quantifiers is not otherwise changed, just the preferred
number of matches.  Do not confuse this use of question
mark with its use as a quantifier in its own right.
Because it has two uses, it can sometimes appear doubled, as in

@example
     \d??\d
@end example

which matches one digit by preference, but can match two if
that is the only way the rest of the pattern matches.

Note that greediness does not matter when specifying addresses,
but can be nevertheless used to improve performance.

@ignore
   If the PCRE_UNGREEDY option is set (an option which is not
   available in Perl), the quantifiers are not greedy by
   default, but individual ones can be made greedy by following
   them with a question mark. In other words, it inverts the
   default behaviour.
@end ignore

When a parenthesized subpattern is quantified with a minimum
repeat count that is greater than 1 or with a limited maximum,
more store is required for the compiled pattern, in
proportion to the size of the minimum or maximum.

@cindex Perl-style regular expressions, single line
If a pattern starts with @code{.*} or @code{.@{0,@}} and the
@code{S} modifier is used, the pattern is implicitly anchored,
because whatever follows will be tried against every character
position in the subject string, so there is no point in
retrying the overall match at any position after the first.
PCRE treats such a pattern as though it were preceded by \A.

When a capturing subpattern is repeated, the value captured
is the substring that matched the final iteration. For example,
after

@example
     (tweedle[dume]@{3@}\s*)+
@end example

@noindent
has matched @samp{tweedledum tweedledee} the value of the
captured substring is @samp{tweedledee}.  However, if there are
nested capturing subpatterns, the corresponding captured
values may have been set in previous iterations. For example,
after

@example
     /(a|(b))+/
@end example

matches @samp{aba}, the value of the second captured substring is
@samp{b}.

@node Backreferences
@appendixsec Backreferences
@cindex Perl-style regular expressions, backreferences

Outside a character class, a backslash followed by a digit
greater than 0 (and possibly further digits) is a back
reference to a capturing subpattern earlier (i.e.  to its
left) in the pattern, provided there have been that many
previous capturing left parentheses.

However, if the decimal number following the backslash is
less than 10, it is always taken as a back reference, and
causes an error only if there are not that many capturing
left parentheses in the entire pattern. In other words, the
parentheses that are referenced need not be to the left of
the reference for numbers less than 10. @ref{Backslash}
for further details of the handling of digits following a backslash.

A back reference matches whatever actually matched the capturing
subpattern in the current subject string, rather than
anything matching the subpattern itself. So the pattern

@example
     (sens|respons)e and \1ibility
@end example

@noindent
matches @samp{sense and sensibility} and @samp{response and responsibility},
but not @samp{sense and responsibility}. If caseful
matching is in force at the time of the back reference, the
case of letters is relevant. For example,

@example
     ((?i)blah)\s+\1
@end example

@noindent
matches @samp{blah blah} and @samp{Blah Blah}, but not
@samp{BLAH blah}, even though the original capturing
subpattern is matched caselessly.

There may be more than one back reference to the same subpattern.
Also, if a subpattern has not actually been used in a
particular match, any back references to it always fail. For
example, the pattern

@example
     (a|(bc))\2
@end example

@noindent
always fails if it starts to match @samp{a} rather than
@samp{bc}.  Because there may be up to 99 back references, all
digits following the backslash are taken as part of a potential
back reference number; this is different from what happens
in @sc{posix} mode. If the pattern continues with a digit
character, some delimiter must be used to terminate the back
reference.  If the @code{X} modifier option is set, this can be
whitespace.  Otherwise an empty comment can be used, or the
following character can be expressed in hexadecimal or octal.

A back reference that occurs inside the parentheses to which
it refers fails when the subpattern is first used, so, for
example, @code{(a\1)} never matches.  However, such references
can be useful inside repeated subpatterns. For example, the
pattern

@example
     (a|b\1)+
@end example

@noindent
matches any number of @samp{a}s and also @samp{aba}, @samp{ababbaa},
etc. At each iteration of the subpattern, the back reference matches
the character string corresponding to the previous iteration.  In
order for this to work, the pattern must be such that the first
iteration does not need to match the back reference.  This can be
done using alternation, as in the example above, or by a
quantifier with a minimum of zero.

@node Assertions
@appendixsec Assertions
@cindex Perl-style regular expressions, assertions
@cindex Perl-style regular expressions, asserting subpatterns

An assertion is a test on the characters following or
preceding the current matching point that does not actually
consume any characters. The simple assertions coded as @code{\b},
@code{\B}, @code{\A}, @code{\Z}, @code{\z}, @code{^} and @code{$}
are described above. More complicated assertions are coded as
subpatterns.  There are two kinds: those that look ahead of the
current position in the subject string, and those that look behind it.

@cindex Perl-style regular expressions, lookahead subpatterns
An assertion subpattern is matched in the normal way, except
that it does not cause the current matching position to be
changed. Lookahead assertions start with @code{(?=} for positive
assertions and @code{(?!} for negative assertions. For example,

@example
     \w+(?=;)
@end example

@noindent
matches a word followed by a semicolon, but does not include
the semicolon in the match, and

@example
     foo(?!bar)
@end example

@noindent
matches any occurrence of @samp{foo} that is not followed by
@samp{bar}.

Note that the apparently similar pattern

@example
     (?!foo)bar
@end example

@noindent
@cindex Perl-style regular expressions, lookbehind subpatterns
finds any occurrence of @samp{bar} even if it is preceded by
@samp{foo}, because the assertion @code{(?!foo)} is always true
when the next three characters are @samp{bar}. A lookbehind
assertion is needed to achieve this effect.
Lookbehind assertions start with @code{(?<=} for positive
assertions and @code{(?<!} for negative assertions. So,

@example
     (?<!foo)bar
@end example

achieves the required effect of finding an occurrence of
@samp{bar} that is not preceded by @samp{foo}. The contents of a
lookbehind assertion are restricted
such that all the strings it matches must have a fixed
length.  However, if there are several alternatives, they do
not all have to have the same fixed length.  This is an extension
compared with Perl 5.005, which requires all branches to match
the same length of string. Thus

@example
     (?<=dogs|cats|)
@end example

@noindent
is permitted, but the apparently equivalent regular expression

@example
     (?<!dogs?|cats?)
@end example

@noindent
causes an error at compile time. Branches that match different
length strings are permitted only at the top level of
a lookbehind assertion: an assertion such as

@example
     (?<=ab(c|de))
@end example

@noindent
is not permitted, because its single top-level branch can
match two different lengths, but it is acceptable if rewritten
to use two top-level branches:

@example
     (?<=abc|abde)
@end example

All this is required because lookbehind assertions simply
move the current position back by the alternative's fixed
width and then try to match.  If there are
insufficient characters before the current position, the
match is deemed to fail.  Lookbehinds, in conjunction with
non-backtracking subpatterns can be particularly useful for
matching at the ends of strings; an example is given at the end
of the section on non-backtracking subpatterns.

Several assertions (of any sort) may occur in succession.
For example,

@example
     (?<=\d@{3@})(?<!999)foo
@end example

@noindent
matches @samp{foo} preceded by three digits that are not @samp{999}.
Notice that each of the assertions is applied independently
at the same point in the subject string. First there is a
check that the previous three characters are all digits, and
then there is a check that the same three characters are not
@samp{999}.  This pattern does not match @samp{foo} preceded by six
characters, the first of which are digits and the last three
of which are not @samp{999}.  For example, it doesn't match
@samp{123abcfoo}. A pattern to do that is

@example
     (?<=\d@{3@}...)(?<!999)foo
@end example

@noindent
This time the first assertion looks at the preceding six
characters, checking that the first three are digits, and
then the second assertion checks that the preceding three
characters are not @samp{999}.  Actually, assertions can be
nested in any combination, so one can write this as 

@example
     (?<=\d@{3@}(?!999)...)foo
@end example

or

@example
     (?<=\d@{3@}...(?<!999))foo
@end example

@noindent
both of which might be considered more readable.

Assertion subpatterns are not capturing subpatterns, and may
not be repeated, because it makes no sense to assert the
same thing several times. If any kind of assertion contains
capturing subpatterns within it, these are counted for the
purposes of numbering the capturing subpatterns in the whole
pattern.  However, substring capturing is carried out only
for positive assertions, because it does not make sense for
negative assertions.

Assertions count towards the maximum of 200 parenthesized
subpatterns.

@node Non-backtracking subpatterns
@appendixsec Non-backtracking subpatterns
@cindex Perl-style regular expressions, non-backtracking subpatterns

With both maximizing and minimizing repetition, failure of
what follows normally causes the repeated item to be evaluated
again to see if a different number of repeats allows the
rest of the pattern to match. Sometimes it is useful to
prevent this, either to change the nature of the match, or
to cause it fail earlier than it otherwise might, when the
author of the pattern knows there is no point in carrying
on.

Consider, for example, the pattern @code{\d+foo} when applied to
the subject line

@example
     123456bar
@end example

After matching all 6 digits and then failing to match @samp{foo},
the normal action of the matcher is to try again with only 5
digits matching the @code{\d+} item, and then with 4, and so on,
before ultimately failing. Non-backtracking subpatterns
provide the means for specifying that once a portion of the
pattern has matched, it is not to be re-evaluated in this way,
so the matcher would give up immediately on failing to match
@samp{foo} the first time.  The notation is another kind of special
parenthesis, starting with @code{(?>} as in this example:

@example
     (?>\d+)bar
@end example

This kind of parenthesis ``locks up'' the part of the pattern
it contains once it has matched, and a failure further into
the pattern is prevented from backtracking into it.
Backtracking past it to previous items, however, works as
normal.

Non-backtracking subpatterns are not capturing subpatterns.  Simple
cases such as the above example can be thought of as a maximizing
repeat that must swallow everything it can.  So,
while both @code{\d+} and @code{\d+?} are prepared to adjust the number of
digits they match in order to make the rest of the pattern
match, @code{(?>\d+)} can only match an entire sequence of digits.

This construction can of course contain arbitrarily complicated
subpatterns, and it can be nested.

@cindex Perl-style regular expressions, lookbehind subpatterns
Non-backtracking subpatterns can be used in conjunction with look-behind
assertions to specify efficient matching at the end
of the subject string. Consider a simple pattern such as

@example
     abcd$
@end example

@noindent
when applied to a long string which does not match.  Because
matching proceeds from left to right, @code{sed} will look for
each @samp{a} in the subject and then see if what follows matches
the rest of the pattern. If the pattern is specified as

@example
     ^.*abcd$
@end example

@noindent
the initial @code{.*} matches the entire string at first, but when
this fails (because there is no following @samp{a}), it backtracks
to match all but the last character, then all but the
last two characters, and so on. Once again the search for
@samp{a} covers the entire string, from right to left, so we are
no better off. However, if the pattern is written as

@example
     ^(?>.*)(?<=abcd)
@end example

there can be no backtracking for the .* item; it can match
only the entire string. The subsequent lookbehind assertion
does a single test on the last four characters. If it fails,
the match fails immediately. For long strings, this approach
makes a significant difference to the processing time.

When a pattern contains an unlimited repeat inside a subpattern
that can itself be repeated an unlimited number of
times, the use of a once-only subpattern is the only way to
avoid some failing matches taking a very long time
indeed.@footnote{Actually, the matcher embedded in @value{SSED}
    tries to do something for this in the simplest cases,
    like @code{([^b]*b)*}.  These cases are actually quite
    common: they happen for example in a regular expression
    like @code{\/\*([^*]*\*)*\/} which matches C comments.}

The pattern

@example
     (\D+|<\d+>)*[!?]
@end example

([^0-9<]+<(\d+>)?)*[!?]

@noindent
matches an unlimited number of substrings that either consist
of non-digits, or digits enclosed in angular brackets, followed by
an exclamation or question mark. When it matches, it runs quickly.
However, if it is applied to

@example
     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
@end example

@noindent
it takes a long time before reporting failure.  This is
because the string can be divided between the two repeats in
a large number of ways, and all have to be tried.@footnote{The
example used @code{[!?]} rather than a single character at the end,
because both @value{SSED} and Perl have an optimization that allows
for fast failure when a single character is used. They
remember the last single character that is required for a
match, and fail early if it is not present in the string.}

If the pattern is changed to

@example
     ((?>\D+)|<\d+>)*[!?]
@end example

sequences of non-digits cannot be broken, and failure happens
quickly.

If changed to

@example
@end example

@node Conditional subpatterns
@appendixsec Conditional subpatterns
@cindex Perl-style regular expressions, conditional subpatterns

It is possible to cause the matching process to obey a subpattern
conditionally or to choose between two alternative
subpatterns, depending on the result of an assertion, or
whether a previous capturing subpattern matched or not. The
two possible forms of conditional subpattern are

@example
     (?(@var{condition})@var{yes-pattern})
     (?(@var{condition})@var{yes-pattern}|@var{no-pattern})
@end example

If the condition is satisfied, the yes-pattern is used; otherwise
the no-pattern (if present) is used. If there are more than two
alternatives in the subpattern, a compile-time error occurs.

There are two kinds of condition. If the text between the
parentheses consists of a sequence of digits, the condition
is satisfied if the capturing subpattern of that number has
previously matched.  The number must be greater than zero.
Consider the following pattern, which contains non-significant
white space to make it more readable (assume the @code{X} modifier)
and to divide it into three parts for ease of discussion:

@example
     ( \( )?   [^()]+   (?(1) \) )
@end example

The first part matches an optional opening parenthesis, and
if that character is present, sets it as the first captured
substring. The second part matches one or more characters
that are not parentheses. The third part is a conditional
subpattern that tests whether the first set of parentheses
matched or not.  If they did, that is, if subject started
with an opening parenthesis, the condition is true, and so
the yes-pattern is executed and a closing parenthesis is
required. Otherwise, since no-pattern is not present, the
subpattern matches nothing.  In other words, this pattern
matches a sequence of non-parentheses, optionally enclosed
in parentheses.

@cindex Perl-style regular expressions, lookahead subpatterns
If the condition is not a sequence of digits, it must be an
assertion.  This may be a positive or negative lookahead or
lookbehind assertion. Consider this pattern, again containing
non-significant white space, and with the two alternatives
on the second line:

@example
     (?(?=...[a-z])
        \d\d-[a-z]@{3@}-\d\d |
        \d\d-\d\d-\d\d )
@end example

The condition is a positive lookahead assertion that matches
a letter that is three characters away from the current point.
If a letter is found, the subject is matched against the first
alternative @samp{@var{dd}-@var{aaa}-@var{dd}} (where @var{aaa} are
letters and @var{dd} are digits); otherwise it is matched against 
the second alternative, @samp{@var{dd}-@var{dd}-@var{dd}}.


@node Recursive patterns
@appendixsec Recursive patterns
@cindex Perl-style regular expressions, recursive patterns
@cindex Perl-style regular expressions, recursion

Consider the problem of matching a string in parentheses,
allowing for unlimited nested parentheses. Without the use
of recursion, the best that can be done is to use a pattern
that matches up to some fixed depth of nesting. It is not
possible to handle an arbitrary nesting depth. Perl 5.6 has
provided an experimental facility that allows regular
expressions to recurse (amongst other things). It does this
by interpolating Perl code in the expression at run time,
and the code can refer to the expression itself. A Perl pattern
tern to solve the parentheses problem can be created like
this:

@example
     $re = qr@{\( (?: (?>[^()]+) | (?p@{$re@}) )* \)@}x;
@end example

The @code{(?p@{...@})} item interpolates Perl code at run time,
and in this case refers recursively to the pattern in which it
appears. Obviously, @code{sed} cannot support the interpolation of
Perl code.  Instead, the special item @code{(?R)} is provided for
the specific case of recursion. This pattern solves the
parentheses problem (assume the @code{X} modifier option is used
so that white space is ignored):

@example
     \( ( (?>[^()]+) | (?R) )* \)
@end example

First it matches an opening parenthesis. Then it matches any
number of substrings which can either be a sequence of
non-parentheses, or a recursive match of the pattern itself
(i.e. a correctly parenthesized substring). Finally there is
a closing parenthesis.

This particular example pattern contains nested unlimited
repeats, and so the use of a non-backtracking subpattern for
matching strings of non-parentheses is important when applying
the pattern to strings that do not match. For example, when
it is applied to

@example
     (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
@end example

it yields a ``no match'' response quickly. However, if a
standard backtracking subpattern is not used, the match runs
for a very long time indeed because there are so many different
ways the @code{+} and @code{*} repeats can carve up the subject,
and all have to be tested before failure can be reported.

The values set for any capturing subpatterns are those from
the outermost level of the recursion at which the subpattern
value is set. If the pattern above is matched against

@example
     (ab(cd)ef)
@end example

@noindent
the value for the capturing parentheses is @samp{ef}, which is
the last value taken on at the top level.

@node Comments
@appendixsec Comments
@cindex Perl-style regular expressions, comments

The sequence (?# marks the start of a comment which continues
ues up to the next closing parenthesis. Nested parentheses
are not permitted. The characters that make up a comment
play no part in the pattern matching at all.

@cindex Perl-style regular expressions, extended
If the @code{X} modifier option is used, an unescaped @code{#} character
outside a character class introduces a comment that continues
up to the next newline character in the pattern.
@end ifset


@page
@node Concept Index
@c @unnumbered Concept Index
@unnumbered 概念の索引

@c This is a general index of all issues discussed in this manual, with the
@c exception of the @code{sed} commands and command-line options.
@c 
以下は，このマニュアルで議論してきたすべての問題の，@code{sed}コマンドと
コマンドラインオプション以外の一般的な索引です．

@printindex cp

@page
@node Command and Option Index
@c @unnumbered Command and Option Index
@unnumbered コマンドとオプションの索引
@c This is an alphabetical list of all @code{sed} commands and command-line
@c options.
@c 
以下は，すべての@code{sed}コマンドとコマンドラインオプションのアルファベッ
ト順のリストです．

@printindex fn

@contents
@bye

@c XXX FIXME: the term "cycle" is never defined...
