【问题标题】:Cannot get sed to update a string [duplicate]无法通过 sed 更新字符串 [重复]
【发布时间】:2021-05-14 20:21:41
【问题描述】:

似乎 sed 没有替换我代码中的字符串。 我打算让它做的是将名为“notification.enable”的属性从 server2 的 false 更改为 true 以激活,并将 server1 中的 true 更改为 false 以停用。 当我在下面单独使用它时它可以工作,但当从函数调用时它不起作用。

sed -i 's/notification.enable=false/notification.enable=true/g' /usr/config/activate.properties

function prompt_activate_server2_config {
activate="notification.enable=true"
deactivate="notification.enable=false"
dir=/usr/config
filename=$dir/activate.properties
output=$(grep "notification" $filename)
if [ -e $filename ];
            then
sed -i 's/$deactivate/$activate/g' "$filename"
echo "Activated in Server 2"
echo $output;date
fi
        }

function prompt_deactivate_server1_config {
    activate="notification.enable=true"
    deactivate="notification.enable=false"
    dir=/usr/config
    filename=$dir/activate.properties
    output=$(grep "notification" $filename)
    if [ -e $filename ];
                then
    sed -i 's/$activate/$deactivate/g' "$filename"
    echo "Deactivated in Server 1"
    echo $output;date
    fi
            }

我正在使用函数,因为我需要从另一台服务器远程执行脚本

所以我用下面的方法来称呼他们。所有“执行”的东西都在上述功能上。我错过了什么?

 if [ "$selection" == 'Activate Config' ]; then

#Activate server1/deactivate server2#
ssh user@server2 "$(typeset -f prompt_activate_server2_config); prompt_activate_server2_config"
sleep 2
ssh user@server1 "$(typeset -f prompt_deactivate_server1_config); prompt_deactivate_server1_config"    
  fi

【问题讨论】:

标签: unix


【解决方案1】:

您需要评估两个变量($deactivate 和 $activate),并使用双引号而不是单引号:

sed -i "s/$deactivate/$activate/g" "$filename"

我会这样写(如果您确实需要在之前/之后打印,请使用 sed 而不是 grep):

  update_config() {    
          local file=$1
          local key=$2 
          local from=$3
          local to=$4                                                 
          [ -e "$file" ] && sed -i "s/\($key=\)$from/\\1$to/g" "$file"         
  }
   
  update_config /usr/config/activate.properties 'notification\.enable' 'false' 'true'

【讨论】:

  • 编辑:我认为它有效,但显然它没有。它仍然没有替换字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 2014-06-21
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多