我有一个看起来像这样的XML文件:

<species compartment="compartment" id="alpha_dash_D_dash_glucose_dash_6P" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">
     </species>
     <species compartment="compartment" id="six_dash_Phospho_dash_D_dash_gluconate" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">
     </species>
     <species compartment="compartment" id="beta_dash_D_dash_Fructose_dash_6P2" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">
     </species>
     <species compartment="compartment" id="beta_dash_D_dash_Glucose" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">
     </species>

每个 id 属性我想用自己的属性替换。我希望我的结尾文件看起来像这样:

<species compartment="compartment" id="id1" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">
     </species>
     <species compartment="compartment" id="id2" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">
     </species>
     <species compartment="compartment" id="id3" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">
     </species>
     <species compartment="compartment" id="id4" initialAmount="0" hasOnlySubstanceUnits="true" constant="false" boundaryCondition="false">

但是,那 id 属性在文件中的其他地方引用:

 <speciesReference constant="true" stoichiometry="1" species="alpha_dash_D_dash_glucose_dash_6P">

该行应更新为:

 <speciesReference constant="true" stoichiometry="1" species="id1">

我尝试使用 sed's/id="(*)"/id="$IdCOUNTER"/g' 但这使一切 id 属性相同。我该如何解决?任何帮助将受到赞赏,谢谢。

有帮助吗?

解决方案

sed -n 's/\s*<species [^>]* id="\([^"]*\).*/\1/p' species.xml |\
  cat -n |\
  sed 's/\s*\([0-9]\+\)\s*/id\1 /' > ids.txt

cp species.xml my_species.xml

while read a b
do
  sed -i 's/"'"$b"'"/"'$a'"/g' my_species.xml
done < ids.txt

假设您的XML文件的格式很好(即,每个标签都在一行上),则可以使用SED和Bash。否则,您需要使用XML解析器的语言。同样的方法将起作用,但细节会有所不同。

制作ID地图以替换。然后,每次遇到以前看到的ID时,都会查找并替换它。

sed 线上的线从一个映射到一个 <species> 标记为编号ID(后斜线允许将行分开几行,以使其可读性)。

复制文件以防止修改原始内容。

由于从ID地图文件中读取每行,因此原始ID的所有出现都被新的编号ID替换。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top