简体   繁体   English

Bash 用变量值替换字符串

[英]Bash replace string with variable value

I'm trying to make a script to replace a string in AndroidManifest.xml with additional permissions defined in a variable, but I'm failing with the pattern definition.我正在尝试制作一个脚本来用变量中定义的附加权限替换AndroidManifest.xml中的字符串,但是我在模式定义方面失败了。

All examples I found use simple replace strings without any special characters like in this case.我发现的所有示例都使用简单的替换字符串,没有像这种情况下的任何特殊字符。

This is what I tried so far这是我到目前为止尝试过的

#!/usr/bin/env bash
CUSTOMPERMISSION=android.permission.INTERNET,android.permission.ACCESS_NETWORK_STATE

echo $CUSTOMPERMISSION
printf "\n"
IFS=','

read -a permissionArray <<< $CUSTOMPERMISSION

printf "There are ${#permissionArray[*]} words in the text.\n\n"

ADDME=""
# Print each value of the array by using the loop
for (( n=0; n < ${#permissionArray[@]}; n++))
do
  ADDME+="<uses-permission android:name=\"${permissionArray[n]}\"/>\n"
done

printf "$ADDME"

REPLACE="<!-- custom_permisions -->"

perl -pe 's/'"${REPLACE}"'/'"${ADDME}"'/' -i AndroidManifest.xml
#sed -i "s/<!-- custom_permisions -->/"${ADDME}"/g" AndroidManifest.xml

I'd like to keep the format of ADDME with a new line so the formatting stays in place.我想用新行保留ADDME的格式,以便格式保持不变。 I tried to add \ for < and - trying to escape them since the script fails with我试图为<添加\并且-由于脚本失败而试图逃避它们

syntax error at -e line 1, near "n<"
Execution of -e aborted due to compilation errors.

I'm not sure where I go wrong, I keep going in circles with search results, so I hoped someone would know the answer.我不确定我在哪里 go 错了,我一直在搜索结果中转圈,所以我希望有人知道答案。

Try this commands试试这个命令

REPLACE='<\!-- custom_permisions -->'
CUSTOMPERMISSION=android.permission.INTERNET,android.permission.ACCESS_NETWORK_STATE
ADDME=$(printf '<uses-permission android:name=\\"%s\\"\\/>\\n' ${CUSTOMPERMISSION//,/ })
ADDME=${ADDME%\\n*}
sed "s|$REPLACE|$ADDME|g" AndroidManifest.xml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM