regex - sed 获取xml属性值

标签 regex bash sed

我有下一个 xml 文件:

<AutoTest>
 <Source>EBS FX</Source>
 <CreateCFF>No</CreateCFF>
 <FoXML descriptor="pb.fx.spotfwd.trade.feed" version="2.0">
   <FxSpotFwdTradeFeed>
     <FxSpotFwd feed_datetime="17-Dec-2014 10:20:09" 
       cpty_sds_id="EBS" match_id="L845586141217" original_trade_id_feed="L80107141217" 
       value_date="20141218" trade_id_external="001-002141880445/5862" match_sds_id="EBSFeedCpty" 
       counter_ccy="USD" trade_id_feed="107" trade_type="S" feed_source_id="80"    quoting_term="M" 
       deal_ccy="GBP" rate="1.5" trade_date="20141217" modified_by="automation"    cpty_side="B" counter_amt="1500000"
       smart_match="0" booking_status_id="10" trade_status_id="22" deal_amt="1000000"  trade_direction="B">
       <Notes />
     </FxSpotFwd>
 </FxSpotFwdTradeFeed>
 <TestCases />
 </FoXML>
</AutoTest>

如何使用sed获取trade_id_external属性的值?
我尝试使用此表达式:sed -n '/trade_id_external/s/.*=//p' ./file.xml 但没有运气

最佳答案

你甚至不需要模式 /trade_id_external/s/// 之前

$ sed -n 's/.*trade_id_external="\([^"]*\).*/\1/p' file
001-002141880445/5862

在基本 sed 中,\(...\)称为捕获组,用于捕获要在最后打印的字符。

通过grep

$ grep -oP 'trade_id_external="\K[^"]*' file
001-002141880445/5862

-P将在 grep 中打开 Perl-regex 模式。所以我们可以在 grep 中使用任何 PCRE 正则表达式 -P参数启用。 \K上面的正则表达式会丢弃之前匹配的字符,即不考虑\K之前存在的模式匹配的字符。

关于regex - sed 获取xml属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27567199/

相关文章:

sed - 删除逗号前一行中的所有内容

linux - 用 sed 替换美元符号

Python 相当于 'grep -C N' ?

bash - 在双引号下重定向包含 git 命令的字符串失败

linux - Hadoop - 列出 HDFS 目录中的所有子目录并将每个目录路径保存到 bash 变量中

linux - 使用shell修改多个文件名

linux - sed - 从字符串中提取特定字符

python - 包含一个词并排除另一个 python

regex - 通过在特定位置添加前缀来编辑文件

regex - 正则表达式替换以构建文件中的版本