エスケープされていないスラッシュをエスケープします。

エスケープされていないスラッシュをエスケープします。

エスケープされたスラッシュとエスケープされていないスラッシュを含む文字列があります。

脱出のためのsed代替品を探していますエスケープされていないスラッシュのみしかし、否定的なLookBehindをサポートしていないようです。

例:

input: "https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https://baz/test.com"

desired output: "https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https:\/\/baz\/test.com"

ベストアンサー1

sed使用POSIX基本正規表現デフォルトでは、Perl準拠の正規表現言語で一般的に見られる予測アサーションと他の幅がゼロのアサーションは除外されます。

代わりに、エスケープされたスラッシュを解放し、変更された文字列のすべてのスラッシュをエスケープします。

sed -e 's@\\/@/@g' -e 's@/@\\/@g'

まず、すべてのインスタンスをに変更し、\/次に/すべて/をに変更します\/。これは@、置換コマンドを防ぐための代替区切り記号です。傾いたつまようじ症候群(ほとんどすべての他の文字を使用できます)。

例:

$ echo '"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https://baz/test.com"' | sed -e 's@\\/@/@g' -e 's@/@\\/@g'
"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https:\/\/baz\/test.com"

テキスト行がシェルの文字列に格納されている場合は、bash次のようにできます。

$ string='"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https://baz/test.com"'
$ string=${string//\\\///}   # leaning toothpick warning!
$ string=${string//\//\\/}
$ printf '%s\n' "$string"
"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https:\/\/baz\/test.com"

上記は変数置換を使用して${variable//pattern/replacement}inをすべてに置き換えます。pattern$variablereplacement

おすすめ記事