匹配 3 个模式(2 个静态,1 个变量)并更改变量 1

匹配 3 个模式(2 个静态,1 个变量)并更改变量 1

我一生都无法解决这个问题,以为我已经解决了,但没有

我有一个 XML 文件,其中包含如下所示的条目

<compat-change description="Flag {@link android.content.Context#BIND_INCLUDE_CAPABILITIES} is used to pass while-in-use capabilities from client process to bound service. In targetSdkVersion R and above, if client is a TOP activity, when this flag is present, bound service gets all while-in-use capabilities; when this flag is not present, bound service gets no while-in-use capability from client." enableAfterTargetSdk="29" id="136274596" name="PROCESS_CAPABILITY_CHANGE_ID"/>

我需要匹配 id 和名称(始终是静态值并且以相同的顺序排列),但更改 Sdk 值(这是可变的)

Sdk="29" id="136274596" name="PROCESS_CAPABILITY"

我确实尝试过

sed -i '/Sdk=\"[0-9]\+\".*id="143937733".*name="PROCESS_CAPABILITY"/ {s/Sdk=\"[0-9]\+\"/Sdk=\"0\"/1;}'

任何建议都非常感激

答案1

您最好使用适当的 XML 工具xmlstarlet,例如

xmlstarlet ed -u '
  //compat-change[@id="136274596"][starts-with(@name,"PROCESS_CAPABILITY")]/@enableAfterTargetSdk
' -v 0 file.xml

前任。

$ xmlstarlet ed -u '//compat-change[@id="136274596"][starts-with(@name,"PROCESS_CAPABILITY")]/@enableAfterTargetSdk' -v 0 file.xml
<?xml version="1.0"?>
<compat-change description="Flag {@link android.content.Context#BIND_INCLUDE_CAPABILITIES} is used to pass while-in-use capabilities from client process to bound service. In targetSdkVersion R and above, if client is a TOP activity, when this flag is present, bound service gets all while-in-use capabilities; when this flag is not present, bound service gets no while-in-use capability from client." enableAfterTargetSdk="0" id="136274596" name="PROCESS_CAPABILITY_CHANGE_ID"/>

如何在 XMLStarlet 中过滤多个属性?

答案2

使用sed

$ sed -E 's/(Sdk=")[^"]*(" id="136274596" name="PROCESS_CAPABILITY)/\10\2/' input_file
<compat-change description="Flag {@link android.content.Context#BIND_INCLUDE_CAPABILITIES} is used to pass while-in-use capabilities from client process to bound service. In targetSdkVersion R and above, if client is a TOP activity, when this flag is present, bound service gets all while-in-use capabilities; when this flag is not present, bound service gets no while-in-use capability from client." enableAfterTargetSdk="0" id="136274596" name="PROCESS_CAPABILITY_CHANGE_ID"/>

相关内容