Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用bash搜索和替换多个句子_Bash_Shell_For Loop_If Statement_Delimiter - Fatal编程技术网

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

使用bash搜索和替换多个句子,bash,shell,for-loop,if-statement,delimiter,Bash,Shell,For Loop,If Statement,Delimiter,现在,我有了搜索和替换单词的脚本。我怎样才能对句子或单词组合做同样的处理呢。 看看我的剧本: 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

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

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
它有效,但只能逐字替换。但是如果我想在几个单词组合上替换几个单词组合。 例如,多尔夫·齐格勒、约翰·塞纳、兰迪·奥尔顿,我想在cm朋克、绿巨人霍根、雷伊·米西奥西奥身上取代他们。在这种情况下我应该做什么。也许我应该处理一些分隔符。在第一种情况下,空格是单词的分隔符,但在这种情况下,我不能使用空格。我能做什么?请帮忙

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
注意:这不安全,仍然可以注射

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"

为什么要分配给变量,然后在数组中使用它们,而不是直接分配给数组?因为它不全是脚本。这是剧本的一部分。我应该在变量中使用输入参数。您如何确定元素的开始和结束位置?在所有文档中,要按照@123的相同方向将参数拆分为句子,在您的示例中,单词按空格或制表符拆分,因为这是默认值,您可以在调用perl之前作为env vars传递,以防止注入,var1=${mycentences[$i]/\/\/\\/\\/}var2=${mycentences2[$i]/\/\/\\/\/}perl-pe的/\Q$ENV{var1}\E/$ENV{var2}/g'@123是的,也可以作为前两个参数传递。它们不是参数,它们是为之后运行的进程设置的环境变量。啊,对了,误解了,以为你在谈论我的建议。
perl -pe 'BEGIN{$oldtext=shift;$newtext=shift}s/\Q$oldtext\E/$newtext/g' "${mysentences[$i]//\//\\/}" "${mysentences2[$i]//\//\\/}" <<<"foo bar baz"