【问题标题】:Looping through unique lines in a txt file with Bash使用 Bash 循环遍历 txt 文件中的唯一行
【发布时间】:2015-06-30 21:21:40
【问题描述】:

我正在循环浏览 txt 文件中的制表符分隔的行。此 txt 文件是 xml/xslt 进程的输出,并且有重复项。下面我正在寻找一个使用 txt 文件的解决方案,但使用 XSLT 的解决方案同样值得赞赏。请查看示例 txt 文件。

txtfile.txt:第 3 行与第 1 行重复

hello@example.com  running  1111
puppy@kennel.com   running  9876
hello@example.com  running  1111
husky@siberia.com  shutdown 1234
puppy@kennel.com   running  9876
hello@example.com  running  1111

我的问题是:可以在循环中跳过重复的行,以便循环只处理唯一的行吗?在这种情况下,如何配置循环第 1、2、4 行并跳过第 3、5、6 行?

我当前读取重复项的工作循环:

while read name status num
do
    echo "<tag1>"
    echo "<tag2>"$name"</tag2>"
    echo "<tag3>"$status"</tag3>"
    echo "<tag2>"$num"</tag2>"
    echo "</tag1>"

done < txtfile.txt

在我的 txtfile 中有数百行,近一半是重复的,所以这对我来说是个大问题!任何想法/解决方案表示赞赏。提前致谢。

【问题讨论】:

  • 可能会使用一个排序的唯一列表,比如&lt;(cat txtfile.tx | sort | uniq)

标签: linux bash shell loops xslt


【解决方案1】:

您可以通过sort -u 读取该文件以消除重复行:

sort -u /your/file | while read ...

【讨论】:

    【解决方案2】:

    我建议使用 awk:

    $ awk '!a[$0]++{print "<tag1>\n<tag2>" $1 "</tag2>\n<tag3>" $2 "</tag3>\n<tag2>" $3 "</tag2>\n</tag1>"}' file
    <tag1>
    <tag2>hello@example.com</tag2>
    <tag3>running</tag3>
    <tag2>1111</tag2>
    </tag1>
    <tag1>
    <tag2>puppy@kennel.com</tag2>
    <tag3>running</tag3>
    <tag2>9876</tag2>
    </tag1>
    <tag1>
    <tag2>husky@siberia.com</tag2>
    <tag3>shutdown</tag3>
    <tag2>1234</tag2>
    </tag1>
    

    条件!a[$0]++ 在第一次看到每一行时评估为真,此后为假。当条件为真时,打印输出。

    基本原理是将$0这一行的内容作为a数组的key。如果记录之间的间距可能有所不同,您可以改用 !a[$1,$2,$3]++,只要 3 个字段相同,无论它们之间的间距如何,它都会将行数计为相同。

    【讨论】:

    • 很好的解决方案!完美地工作..虽然我有点懒得编写/编辑广泛的 awk 命令,如果我可以采用另一种方式(排序 -u 由 Costi 发布)。当我有能力达到 15 个代表时,我肯定会投票。
    猜你喜欢
    • 2021-12-09
    • 2013-04-08
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2014-11-19
    • 1970-01-01
    相关资源
    最近更新 更多