sed コマンドの組み合わせに関するヘルプ (構文)

sed コマンドの組み合わせに関するヘルプ (構文)

次のような多くの行を含むファイルがあります

, foo = $true
, foo = $false
foo = $true, <--- single space after comma
foo = $false, <-- single space after comma

これらの文字列を置き換えるには

#!/bin/bash

sed -i 's/, foo = $true/bar/g' file
sed -i 's/, foo = $false/bar/g' file
sed -i 's/foo = $true, /bar/g' file
sed -i 's/foo = $false, /bar/g' file

あるいは、鎖でつなぐのも同じくらい悪い

sed -i -e 's/, foo = $true/bar/g' -e 's/, foo = $false/bar/g' -e 's/foo = $true, /bar/g' ... file

しかし、単一の sed コマンドを使用してすべての反復を実行する方法はあるのでしょうか?

sed -i 's/[,\ ].*foo = [$false\|$true][,\ ]/bar/g' file

答え1

sed -Ei 's/,{,1} {,1}foo = \$(true|false),{,1} {,1}/bar/g' file
sed -Ei 's/(, ){,1}foo = \$(true|false)(, ){,1}/bar/g' file

-Eフラグは拡張正規表現を有効にし、エスケープせずにメタ文字を使用できるようにします(){}|

  • (, ){,1}は 0 回 (暗黙的) から 1 回まで一致します,

  • \$(true|false)$trueまたはと一致します$false


覚えておいてください

sed -i -e 's/, foo = $true/bar/g' -e 's/, foo = $false/bar/g' -e 's/foo = $true, /bar/g' ... file

単一の sed コマンドですが、さまざまなスクリプト (-eフラグごとに 1 つ) があります。

関連情報