sed(1)
pattern space
非常に詳しい使い方
Common one-line sed scripts
ワンライナーでよく使われるsedコマンド集
以下のファイルを操作する。
code:plain
apple juice
banana boats
canada flag
danger zone
-nフラグはno outputの意味
-nフラグを有効にしない限り、sedの標準的な動作は変更されていない部分を含めてファイル全体を出力すること。
2, 3行目を除いて出力
code:plain
cat -n textfile | sed 2,3d
1 apple juice
4 danger zone
2行目から最後の行まで出力
code:plain
cat -n textfile | sed -n 2,$p
2 banana boats
3 canada flag
4 danger zone
sコマンドで置換操作
s/regexp/replacement/
Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.
&でマッチしたテキストを指す
code:shell
echo Hello world | sed 's/world/&!/g'
# Hello world!
file.txtにあるamdの行を数える
code:sh
sed -n /amd/p file.txt | wc -l
/NスイッチでLHSにおけるN番目のマッチを参照する
Replace the Nth match of the pattern on the LHS, where N is an integer between 1 and 512. If N is omitted, the default is to replace the first match only.
code:sh
echo bang beng bing bong bung | sed 's/a-z*/*&*/1' *bang* beng bing bong bung
echo bang beng bing bong bung | sed 's/a-z*/*&*/3' bang beng *bing* bong bung