简体   繁体   中英

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.

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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