【问题标题】:Replacing unique identifiers in a file替换文件中的唯一标识符
【发布时间】:2013-11-19 17:54:04
【问题描述】:

我有一个如下所示的 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 属性都相同。我该如何解决这个问题?任何帮助表示赞赏,谢谢。

【问题讨论】:

    标签: file replace sed uniqueidentifier


    【解决方案1】:
    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 行将&lt;species&gt; 标记中的每个id 映射到一个编号的id(反斜杠允许将该行分成几行以便于阅读)。

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

    当从 id 映射文件中读取每一行时,所有出现的原始 id 都将替换为新的编号 id。

    【讨论】:

    • 感谢@traybold,我打算使用 xml 解析器并手动修改它们。
    猜你喜欢
    • 2020-03-25
    • 2012-04-25
    • 1970-01-01
    • 2021-10-30
    • 2014-02-15
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 2013-02-19
    相关资源
    最近更新 更多