使用 bash 搜索和替换几个句子

Search and replace of several sentences using bash

现在,我有了搜索和替换单词的脚本。我怎样才能对句子或单词组合做同样的事情。 查看我的脚本:

first_words="wwe wwf ziggler"
second_words="tna njpw okada"

mywords=( $first_words )
mywords2=( $second_words )

if [ ${#mywords[@]} != ${#mywords2[@]} ];then
        echo "you should use the same count of words"
        exit 1
else
        echo "you are using the same count of words, continue ..."
fi

for ((i=0;i<"${#mywords[@]}";++i)); do
        sed -i "s/${mywords[$i]}/${mywords2[$i]}/g" text.txt
done

有效,但只能逐字替换。但是如果我想在几个单词组合上替换几个单词组合。 例如 "dolph ziggler, john cena, randy orton" 我想在 "cm punk, hulk hogan, rey mysterio" 上替换。在这种情况下我应该做什么。可能我应该处理一些定界符。在第一种情况下,space 是单词的分隔符,但在这种情况下,我不能使用 space。我可以做什么 ?请帮忙

mysentences=( "first sentence" "second sentence" )
mysentences2=( "new first" "new second" )
...
for ((i=0;i<"${#mysentences[@]}";++i)); do
    sed -i "s/${mysentences[$i]}/${mysentences2[$i]}/g" text.txt
done

警告,如果句子可以包含 /,则必须对其进行转义,如果它们可以包含在正则表达式中具有特殊含义的字符,则可以在 perl 中使用 \Q\E 进行转义.

perl -i -pe 's/\Q'"${mysentences[$i]//\//\/}"'\E/'"${mysentences2[$i]//\//\/}/g" text.txt

注意:不安全,注射还是可以的

mysentences=( "bar" )
mysentences2=( '@{[`echo ok >&2`]}' )

perl -pe 's/\Q'"${mysentences[$i]//\//\/}"'\E/'"${mysentences2[$i]//\//\/}/g" <<<"foo bar baz"

将句子作为参数传递以防止注入

perl -pe 'BEGIN{$oldtext=shift;$newtext=shift}s/\Q$oldtext\E/$newtext/g' "${mysentences[$i]//\//\/}" "${mysentences2[$i]//\//\/}" <<<"foo bar baz"