use*_*487 4 regex bash shell perl
我想用数组中的字符串替换某些文本的中间部分。
#!/bin/bash
array=(1 2 3 4 5 6)
for i in "${array[@]}"; do
# doesn't work
echo "some text" | perl -pe 's|(some).*(text)|\1$i\2|'
done
Run Code Online (Sandbox Code Playgroud)
我使用perl regex而不是sed,因为它提供了更轻松的非贪婪匹配支持。在其中获取$ i值的正确语法是什么?
只需用双引号替换正则表达式周围的单引号即可。
#!/bin/bash
array=(1 2 3 4 5 6)
for i in "${array[@]}"; do
echo "some text" | perl -pe "s|(some).*(text)|\1$i\2|"
done
Run Code Online (Sandbox Code Playgroud)
单引号不会扩展变量。