【问题标题】:Search and replace of several sentences using bash使用 bash 搜索和替换几个句子
【发布时间】:2017-06-07 11:47:32
【问题描述】:

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

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”上替换。在这种情况下我应该怎么做。也许我应该处理一些分隔符。在第一种情况下,空格是单词的分隔符,但在这种情况下,我不能使用空格。我可以做什么 ?请帮忙。

【问题讨论】:

  • 为什么要赋值给变量,然后在数组中使用它们,而不是直接赋值给数组?
  • 因为它不是所有的脚本。它是脚本的一部分。我应该在变量中使用输入参数。
  • 你如何确定元素的开始和结束位置?
  • 在所有文档中
  • 与@123 的方向相同,如何将参数拆分为句子,在您的示例中,单词被空格(或制表符)分隔,因为这是默认设置

标签: bash shell for-loop if-statement delimiter


【解决方案1】:
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"

【讨论】:

  • 您可以在调用 perl 之前将其作为 env vars 传递以防止注入,var1="${mysentences[$i]//\//\\/}" var2="${mysentences2[$i]//\//\\/}" perl -pe 's/\Q$ENV{"var1"}\E/$ENV{"var2"}/g' &lt;&lt;&lt;"foo bar baz"
  • @123 是的,也可以作为前两个参数传递
  • 它们不是参数,它们是为随后运行的进程设置的环境变量。
  • 啊对,误会了,以为你在说我的建议。
猜你喜欢
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
  • 1970-01-01
  • 2011-02-17
  • 2019-01-06
  • 1970-01-01
相关资源
最近更新 更多