linux - 比较一个文件中的数字,并在该数字出现在 shell 脚本中的字符串内时将其与文件中的数字进行匹配

标签 linux bash shell sh

我有两个文件。一个仅包含一列随机整数。 1.数据:

    2
    4
    7
    9

其他文件 (2.dat) 包含以下内容:

    <event id="2">
    <rwgt>
    <wgt id="1">0.866665</wgt>
    <wgt id="2">0.866665</wgt>
    <event id="3">
    <rwgt>
    <wgt id="1">0.901111</wgt>
    <wgt id="2">0.901111</wgt>
    ....

我想将1.dat中的每个数字与里面的数字进行比较

    <event id=" "> tag

当匹配时我想要里面的数字

    <wgt id="1"> </wgt> tag

我正在使用 shell 脚本中的第一个文件

    #! /bin/bash
    while read first ; 
    do
    echo "$first"
    done < 1.dat

但是在 do 循环内我仍然无法合并 2.dat 文件。 任何人都可以帮忙吗?

最佳答案

为了扩展我上面的评论,如果您的真实文件是有效的 XML,如下所示:

<?xml version="1.0"?>
<root>
  <event id="2">
    <rwgt>
      <wgt id="1">0.866665</wgt>
      <wgt id="2">0.866665</wgt>
    </rwgt>
  </event>
  <event id="3">
    <rwgt>
      <wgt id="1">0.901111</wgt>
      <wgt id="2">0.901111</wgt>
    </rwgt>
  </event>
</root>

然后您可以使用 XML 解析器(例如 xmllint)来提取您感兴趣的值:

#!/bin/bash

while read id; do
    val=$(xmllint --xpath "//event[@id='$id']//wgt[@id=1]/text()" 2.dat 2>/dev/null)
    [[ -n $val ]] && echo "$val"
done < 1.dat

这里我使用了 xpath 表达式来获取 <wgt> 的文本内容元素为 id=1 ,在<event>内具有匹配 id 的元素为文件中的值。如果没有匹配的内容,则会向 stderr 打印一条消息,因此我将其重定向到 /dev/null来压制它。

输出:

0.866665

关于linux - 比较一个文件中的数字,并在该数字出现在 shell 脚本中的字符串内时将其与文件中的数字进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29192863/

相关文章:

linux - 移除进程的RT优先级

linux Bash - 读取文件内容,将它们存储在变量中并创建网络配置文件

python - 如何在 debian 10 上使用 checkinstall 安装 python3.8?

linux - Debian 镜像持续增长

linux - Grep 包含 'n' 给定用户输入的字母数的单词

linux - 在 heredoc 中使用时如何转义 awk 的内置变量

shell - 当不在 $HOME 时让提示只显示目录?

linux - 整数表达式预期错误。

shell - 如何使用 Chef 配方添加 cron 作业条目

linux - 构建mesos时出现libtool错误