首页 > 解决方案 > 替换 bash 和 azuredevops 类中的字符串(ios xamarin 管道)

问题描述

我正在尝试编写一个 bash 脚本来更改我的 azure devops 管道的类中的字符串。但无法使其工作。

从https://github.com/Microsoft/appcenter-build-scripts-examples/blob/master/xamarin/app-constants/appcenter-pre-build.sh复制脚本

我的 bash 尝试:

  1. 添加了一个 bash 任务(内联脚本)
  2. 创建了一个环境变量 API_URL,其值为 ="https://production.com/api"
  3. 我的班级要改变

    namespace Core
    {
       public class AppConstant
       {
         public const string ApiUrl = "https://production.com/api";
         public const string AnotherOne="AAA";
       }
    }        
    

我的剧本

    if [ ! -n "$API_URL" ]
    then
        echo "You need define the API_URL variable"
        exit
    fi

    APP_CONSTANT_FILE=$(Build.SourcesDirectory)/MyProject/Core/AppConstant.cs

    if [ -e "$APP_CONSTANT_FILE" ]
    then
        echo "Updating ApiUrl to $API_URL in AppConstant.cs"
        sed -i '' 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

        echo "File content:"
        cat $APP_CONSTANT_FILE
    fi

为什么我的变量没有改变?非常感谢

标签: bashazure-devops

解决方案


您的脚本是正确的,将获得所需的输出,仅在 sed -i 后删除双撇号:

sed -i 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

但是,我也会至少将 regexp 更改为此,因为 . (dot) 保留为正则表达式中的任何字符:

sed -i 's#ApiUrl = "[a-z:\./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

甚至为此(为了在引号之间取任何字符):

sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

测试:

$ cat > developer9969.txt
namespace Core
{
   public class AppConstant
   {
     public const string ApiUrl = "https://production.com/api";
   }
}

API_URL='https://kubator.com/'
APP_CONSTANT_FILE='./developer9969.txt'
sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

$ cat $APP_CONSTANT_FILE
namespace Core
{
   public class AppConstant
   {
     public const string ApiUrl = "https://kubator.com/";
   }
}

推荐阅读