sed キャプチャパラメータ

sed キャプチャパラメータ

複数のHTMLファイルに表示される内容を置き換えようとしています。新しいサブドメイン名でファイルを更新したいと思います。

以前のURLは次のとおりです。

https://123.olddomain.com/wp-content/

新しいものは次のようになります。

https://newdomain.com/static/123.newdomain.com/wp-content/

次の式では、すべてのサブドメインhtmlファイルを一度に更新しようとします。

sudo find . -type f -exec sed -i 's+https:\/\/\([0-9]\).olddomain.com\/wp-content\/+https:\/\/newdomain.com\/static\/$1.newdomain.com\/wp-content\/+g' {} +

$ 1が私のr表現をキャプチャできないようです。 [0-9]

どんなアドバイスもありがとうございます。

ベストアンサー1

この種の問題を処理する慣用的な方法は、シェル変数を使用し、その変数がsed置換の左側または右側に表示されるかどうかを正確に引用することです。

## make the old var pluggable in the lhs
old='https://123.olddomain.com/wp-content/'
old_lhs=$old
for c in \\ \[ \^ \$ . \* / ;do
old_lhs=${old_lhs//"$c"/\\"$c"}
done

### make the new var pluggable on rhs
new='https://newdomain.com/static/123.newdomain.com/wp-content/'
new_rhs=$new
for c in \\ \& $'\n' /;do
  new_rhs=${new_rhs//"$c"/\\"$c"}
done

## now traverse the tree and detect files
## that have the old domain string in it
# then pass them in multiple chunks to sed
find . -type f \
  -exec grep -qFe "$old" {} \; \
  -exec sed -i -e "s/$old_lhs/$new_rhs/g" {} + \
;

おすすめ記事