sed 捕获参数

sed 捕获参数

我正在尝试替换一堆 html 文件中出现的情况。我想用新的子域名更新文件。

旧的网址看起来像这样:

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

处理此类问题的惯用方法是使用 shell 变量并正确引用该变量是出现在 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" {} + \
;

答案2

感谢您的所有建议,非常有帮助,我最终使它与此一起工作:

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

\1正在捕获子域中包含并由 标识的所有数字\([0-9]*\)

相关内容