【问题标题】:BASH to compare two fields integrating informations from another fileBASH 比较集成来自另一个文件的信息的两个字段
【发布时间】:2018-12-06 13:24:15
【问题描述】:

我有以下两个文本文件:

水果.txt

nectarine      strawberry
orange         peach
grape          apple
mango          watermelon

数字.txt

strawberry    57
apple         48
mango         40
peach         44
watermelon    60
nectarine     46
orange        72   
grape         39

在 fruits.txt 中,我想每行只保留 ​​2 个水果中的一个。 删除的应该是具有更高对应数字的那个(c.f. numbers.txt)。 输出如下所示:

nectarine
peach
grape
mango

如何在 bash 中实现这一目标?

【问题讨论】:

  • 你有什么尝试吗?
  • 发布您的研究成果以及问题

标签: bash awk sed highest


【解决方案1】:

您可以使用readwhile 循环。 例如:

#!/bin/bash

# read numbers.txt into associate array
declare -A a
while read k v; do
    a[$k]=$v
done < numbers.txt

# process the fruits.txt
while read l r; do
    (( a[$l] > a[$r] )) && l=$r
    echo $l
done < fruits.txt

将给出所需的输出

【讨论】:

    【解决方案2】:

    你可以使用这个awk 命令:

    awk 'FNR == NR {num[$1]=$2; next} {
    print (num[$1] < num[$2] ? $1 : $2)}' numbers.txt fruits.txt
    

    nectarine
    peach
    grape
    mango
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2021-12-11
      • 1970-01-01
      相关资源
      最近更新 更多