広告

暗号資産取引所の登録特典

登録するだけで受け取れる特典です。条件は各取引所の告知をそのまま載せています。

sed

テキスト処理

書き方

sed -i 's/[old]/[new]/g' [file]

行単位で文字列を書き換えます。その場で直す -i が GNU と BSD で違い、末尾に g が無いと各行の最初の一つだけが変わります。

よく使うオプション

オプション意味
s/a/b/gReplace a with b; without the trailing g only the first per line
-iEdit in place. GNU takes -i alone, BSD and macOS need -i ""
-EExtended regex; BSD also accepts -r for GNU compatibility
-nPrint nothing unless a command says to, usually with p
-eAdd another expression to the script
-fRead the script from a file

例

sed -i 's/foo/bar/g' file.txt

Replaces every foo in place (GNU).

sed -i '' 's/foo/bar/g' file.txt

The same on macOS, with the empty argument.

sed -n '10,20p' file.txt

Prints only lines 10 to 20.

パイプでつないで使うのが本来の形です。ひとつで全部やるより、三つつないだ方が短くなります。

読み方

  • 角括弧 [ ] は省いてよい部分です。
  • 三点 … は複数並べられるという意味です。
  • オプションは大文字小文字を区別します — -r と -R が別物のコマンドもあります。

よくある質問

Qsed は何をしますか。

行単位で文字列を書き換えます。その場で直す -i が GNU と BSD で違い、末尾に g が無いと各行の最初の一つだけが変わります。

Qどう打ちますか。

sed -i 's/[old]/[new]/g' [file] — 角括弧は省いてよい部分です。

Qよく使うオプションはいくつですか。

ここにまとめたのは6個です。全部は man sed にあります。このコマンドはテキスト処理の仲間です。

関連するコマンド

man ページ: man sed