▼すべてを開く。
▲すべてを閉じる。
$ cat Sep2005.txt 41th Monthly Meeting Date: Sep.9 (Fri),2005 Time: 18:30-21:00 Place: A4 Engineering Dep. Room 103 Subject: Refer to the attached file
$ cat change s/41th/42th/ s/Sep/Oct/ s/9/7/ s/103/101/
$ sed -f change < Sep2005.txt 42th Monthly Meeting Date: Oct.7 (Fri),2005 Time: 18:30-21:00 Place: A4 Engineering Dep. Room 101 Subject: Refer to the attached file
sedコマンドで、-fオプション、編集コマンドを記述したスクリプトファイル「change」を指定し、リダイレクト「<」で編集するファイル「Sep2005.txt」をsedコマンドに与える。これで、ファイル「change」に記述された編集コマンドがファイル「Sep2005.txt」に対して実行される。
複数の置換を行うときにファイルに編集コマンドを記述しておく。この編集コマンドは、1行に1つのコマンドを記述する。
$ sed -f change < Sep2005.txt > Oct2005.txt
ファイルに保存する場合は、コマンドの出力をリダイレクト「>」でファイル「Oct2005.txt」に指定する。
$ sed -f change < Sep2005.txt | tee Oct2005.txt 42th Monthly Meeting Date: Oct.7 (Fri),2005 Time: 18:30-21:00 Place: A4 Engineering Dep. Room 101 Subject: Refer to the attached file
ファイルに保存して、画面にも表示する場合は、teeコマンドを使う。sedコマンドの出力をパイプ「|」でteeコマンドに渡し、保存するファイル「Oct2005.txt」を指定する。これで、コマンドの実行結果がファイルに保存され、画面にも表示される。
$ cat desc.txt Sed is a streaming editor that is used to perform basic text transformations on an input streaming (a file or input from a pipeline).sedコマンドで置換文字列を指示し、ファイルを与える
$ sed 's/streaming/stream/g' < desc.txt Sed is a stream editor that is used to perform basic text transformations on an input stream (a file or input from a pipeline).
sedコマンドで、置換文字列を「's/streaming/stream/g'」、ファイル「desc.txt」をリダイレクトでコマンドに与えると、ファイル中の文字列「streaming」をすべて「stream」に変換する。
置換文字列の指定方法 |
---|
's/置換する文字列/新しい文字列/g' |
正規表現などがシェルに解釈されないように引用符「'」で囲む
trコマンドに置換を指示する「s」
「/」に続いて置換する文字列を指定
「/」に続いて新しい文字列を指定
「/」で閉じる
trコマンドにすべて置換を指示する「g」
$ cat desc.txt Sed is a streaming editor that is used to perform basic text transformations on an input streaming (a file or input from a pipeline).
$ sed 's/streaming/stream/' < desc.txt Sed is a stream editor that is used to perform basic text transformations on an input streaming (a file or input from a pipeline).
sedコマンドで、置換文字列を「's/streaming/stream/'」、ファイル「desc.txt」をリダイレクトでコマンドに与えると、各行で最初に見つかった文字列「streaming」を「stream」に変換する。同じ行の中にある2つ目の「streaming」は置換されない。
$ cat desc.txt | sed 's/streaming/stream/'
catコマンドの出力をパイプでsedに送っても同様の結果を得られる。
置換文字列の指定方法 |
---|
's/置換する文字列/新しい文字列/' |
正規表現などがシェルに解釈されないように引用符「'」で囲む
trコマンドに置換を指示する「s」
「/」に続いて置換する文字列を指定
「/」に続いて新しい文字列を指定
「/」で閉じる。
各行が短く改行されている場合、結果としてすべて置換される場合がある。
catコマンドで編集するファイルを見る$ cat desc.txt Sed is a streaming editor that is used to perform basic text transformations on an input streaming (a file or input from a pipeline).
単語を1つだけ置換するつもりでコマンドを実行しても、行が短いために結果的にすべての文字列が変換されてしまう。
sedコマンドで置換パターンを指示し、ファイルを与える$ sed 's/streaming/stream/' < desc.txt Sed is a stream editor that is used to perform basic text transformations on an input stream (a file or input from a pipeline).