如何创建android shell脚本来编辑xml中的字符串

时间:2012-11-13 05:36:49

标签: android xml bash unix

这是我尝试编辑的xml文件

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="public_checkins" value="false" />
<string name="checkins">[{&quot;storeName&quot;:&quot;Rundle Street&quot;,&quot;prize&quot;:&quot;price_fwh&quot;,&quot;checkinTime&quot;:1352717951195,&quot;prizeClaimed&quot;:false,&quot;storeId&quot;:57,&quot;expired&quot;:false},{&quot;storeName&quot;:&quot; Street&quot;,&quot;prize&quot;:&quot;price_fmf&quot;,&quot;checkinTime&quot;:1352717723886,&quot;prizeClaimed&quot;:false,&quot;storeId&quot;:57,&quot;expired&quot;:false}]</string>
*<string name="uuid">30212345-0c1e-dcb-974e-5effa7f016be</string>*
</map>

我正在尝试创建一个shell脚本来编辑字符串uuid,并在每次运行脚本时用随机生成的数字序列替换uuid。

以下是我提出的脚本。

#!/system/bin/sh

set number=$RANDOM

echo "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="public_checkins" value="false" />
<string name="checkins">[{&quot;storeName&quot;:&quot; Street&quot;,&quot;prize&quot;:&quot;price_fwh&quot;,&quot;checkinTime&quot;:1352717951195,&quot;prizeClaimed&quot;:false,&quot;storeId&quot;:57,&quot;expired&quot;:false},{&quot;storeName&quot;:&quot;Rundle Street&quot;,&quot;prize&quot;:&quot;price_fmf&quot;,&quot;checkinTime&quot;:1352717723886,&quot;prizeClaimed&quot;:false,&quot;storeId&quot;:57,&quot;expired&quot;:false}]</string>
<string name="uuid">302$number-0c1e-dcb-974e-5effa7f016be</string>
</map>
" > /data/data/com.app/shared_prefs/app.xml

2 个答案:

答案 0 :(得分:0)

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="uuid">302%1$s-0c1e-dcb-974e-5effa7f016be</string>
</map>

现在您可以使用此格式获取如下所示的字符串

String uuid = String.format(getResources().getString(R.string.uuid), YourUUIDNumber);

您将收到完整的字符串

302xxxxxx-0c1e-dcb-974e-5effa7f016be

其中xxxxxxx是您在String的格式方法中传递的值。

答案 1 :(得分:0)

Perl更适合这个

file=/data/data/com.app/shared_prefs/app.xml
mv $file $file.bak
{
 arr=({0..9} {a..f})
 while IFS=\> read -d\< tag str; do
  if [[ $tag = *'name="uuid"'* ]]; then
   randomstr=
   for ((i=0;i<32;i++)); do
    if ((i%4==0 && i/4>=2 && i/4<6)); then
     randomstr=$randomstr-
    fi
    randomstr=$randomstr${arr[RANDOM%16]}
   done
  printf "%s" "$tag${str:+>}$randomstr<"
  else
   printf "%s" "$tag${str:+>}$str<"
  fi
 done
 printf "%s\n" "$tag>"
} <$file.bak >$file
# rm $file.bak #