sed
テキスト処理
書き方
sed -i 's/[old]/[new]/g' [file]行単位で文字列を書き換えます。その場で直す -i が GNU と BSD で違い、末尾に g が無いと各行の最初の一つだけが変わります。
よく使うオプション
| オプション | 意味 |
|---|---|
| s/a/b/g | Replace a with b; without the trailing g only the first per line |
| -i | Edit in place. GNU takes -i alone, BSD and macOS need -i "" |
| -E | Extended regex; BSD also accepts -r for GNU compatibility |
| -n | Print nothing unless a command says to, usually with p |
| -e | Add another expression to the script |
| -f | Read the script from a file |
例
sed -i 's/foo/bar/g' file.txtReplaces every foo in place (GNU).
sed -i '' 's/foo/bar/g' file.txtThe same on macOS, with the empty argument.
sed -n '10,20p' file.txtPrints only lines 10 to 20.
パイプでつないで使うのが本来の形です。ひとつで全部やるより、三つつないだ方が短くなります。
読み方
- 角括弧 [ ] は省いてよい部分です。
- 三点 … は複数並べられるという意味です。
- オプションは大文字小文字を区別します — -r と -R が別物のコマンドもあります。
よくある質問
Q. sed は何をしますか。
行単位で文字列を書き換えます。その場で直す -i が GNU と BSD で違い、末尾に g が無いと各行の最初の一つだけが変わります。
Q. どう打ちますか。
sed -i 's/[old]/[new]/g' [file] — 角括弧は省いてよい部分です。
Q. よく使うオプションはいくつですか。
ここにまとめたのは6個です。全部は man sed にあります。このコマンドはテキスト処理の仲間です。
関連するコマンド
man ページ: man sed