【问题标题】:shell bash-to to sed with a string that includes "shell bash-to 使用包含 "
【发布时间】:2014-01-21 09:45:14
【问题描述】:

我正在尝试用包含变量和引号的字符串替换一些文本,例如:

test "$x" "1" "0" ""

其中 x 是来自数组的参数。

我不知道该怎么做,通常我只会在替换字符串值周围使用“”,以便它扩展 x 值,但显然这不会起作用,因为我的字符串包含“” 到目前为止,她是我的命令:

cat $FILE | sed 's|/#replace|test "'"$x"'" "1" "0" "" '|g' > $NEW_FILE

但这不起作用。任何帮助将不胜感激。

【问题讨论】:

  • 单引号数是奇数,所以估计|g前面的单引号是多余的

标签: arrays string bash shell sed


【解决方案1】:

这个版本似乎做你想做的事:

$ x=ABC ; echo '/#replace' | sed 's|/#replace|test "'"$x"'" "1" "0" "" |g' 
test "ABC" "1" "0" "" 

sed 命令由三个字符串组成。为了清楚起见,我在它们之间添加了空格:

's|/#replace|test "' "$x" '" "1" "0" "" |g'  # Don't try to use this form.  It is for explication only.

sed 命令的第一部分和第三部分用单引号括起来,以防止 shell 解释。中间字符串是唯一在双引号中的字符串,因此 $x 被解释。

【讨论】:

    【解决方案2】:

    试试这个 sed:

    sed "s|/#replace|test \"$x\" \"1\" \"0\" \"\"|g" "$FILE" > "$NEW_FILE"
    

    【讨论】:

      【解决方案3】:

      你应该这样做:

      FILEPATH="/path/to/SourceFile"
      sed 's|search|replace|' $FILEPATH  > /path/to/EditedFile-new
      

      【讨论】:

        猜你喜欢
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        • 2015-11-22
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 2010-09-27
        • 1970-01-01
        相关资源
        最近更新 更多