我正在尝试编写一个 bash 脚本来为我的 azure devops 管道更改类中的字符串。但无法使其工作。
我的 bash 尝试:
- 添加了一个 bash 任务(内联脚本)
- 创建了一个值为 ="https://production.com/api"的环境变量 API_URL
我要改变的类(class)
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
为什么我的变量没有改变?非常感谢
最佳答案
你的脚本是正确的并且会得到想要的输出,只需要删除 sed -i 之后的双撇号:
sed -i 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
不过,我至少也会将正则表达式更改为此,因为 . (点)保留为正则表达式中的任何字符:
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/";
}
}
关于bash - 替换类 bash 和 azuredevops 中的字符串(ios xamarin 管道),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53407321/