![匹配 3 个模式(2 个静态,1 个变量)并更改变量 1](https://linux22.com/image/210180/%E5%8C%B9%E9%85%8D%203%20%E4%B8%AA%E6%A8%A1%E5%BC%8F%EF%BC%882%20%E4%B8%AA%E9%9D%99%E6%80%81%EF%BC%8C1%20%E4%B8%AA%E5%8F%98%E9%87%8F%EF%BC%89%E5%B9%B6%E6%9B%B4%E6%94%B9%E5%8F%98%E9%87%8F%201.png)
我一生都无法解决这个问题,以为我已经解决了,但没有
我有一个 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"/>
答案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"/>