【问题标题】:how to extract a value between two tags in unix如何在unix中提取两个标签之间的值
【发布时间】:2016-02-03 21:49:09
【问题描述】:
<trans-unit id="OText.Meetwithcustomer">
            <source>Meet with customer</source>
            <target>\u015eedin\u0163\u0103 cu clientul
</target>
            <note>A step in the sales stage of type qualification in a bid and in a project.</note>
            <note>ID:240645::TYPE:Text/Data</note>
         </trans-unit>
         <trans-unit id="OText.Negotiate">
            <source>Negotiate</source>
            <target>Negociere</target>
            <note>A step in the sales stage of type closed in a standard and in a project.</note>
            <note>ID:240646::TYPE:Text/Data</note>
         </trans-unit>

我将 trans-unit id 传递给脚本,在脚本内部,我试图获取该 trans-unit id 的目标标记值。 trans-unit id 值可以是 OText.Meetwithcustomer 或 OText.Negotiate。如果是 OText.Meetwithcustomer ,我需要获取值 \u015eedin\u0163\u0103 cu clientul,如果是 OText.Negotiate,我需要获取 Negociere。

如何在脚本文件中执行此操作。我正在寻找使用 sed/awk/grep 的答案 感谢您的帮助。

【问题讨论】:

  • 您的样本与您的陈述相矛盾&lt;target&gt;Negociere&lt;/target&gt;
  • 我将 trans-unit id 传递给脚本,并且在脚本内部,我试图获取该 trans-unit id 的目标标签值。 trans-unit id 值可以是 OText.Meetwithcustomer 或 OText.Negotiate。如果是 OText.Meetwithcustomer ,我需要获取值 \u015eedin\u0163\u0103 cu clientul,如果是 OText.Negotiate,我需要获取 Negociere。

标签: unix awk sed grep


【解决方案1】:

使用 XML 感知工具来解析和处理 XML。例如xsh:

open file.xml ;
echo //trans-unit[@id='OText.Meetwithcustomer']/target ;

//trans-unit[@id='OText.Meetwithcustomer']/target 字符串称为XPath 表达式。支持 XPath 的工具有很多。

【讨论】:

  • 谢谢。您能否分享一个不使用任何 xml 解析器的答案?
  • @arun:关键是你不需要它。它脆弱、不可靠且难以维护。使用 XML 感知工具是可行的方法。
【解决方案2】:

一个不强大的awk hack

$ awk -v RS="</trans-unit>" '/OText.Meetwithcustomer/' file
| awk -v FS="<target>" 'NF>1{print $2}'


\u015eedin\u0163\u0103 cu clientul

说明:基于xml结构提取带有搜索词的记录。再次从该记录中捕获目标标记旁边的文本。您可以合并脚本,但我认为这样更好。

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 2015-08-11
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 2016-12-21
    • 1970-01-01
    相关资源
    最近更新 更多