【问题标题】:Compare strings using awk command使用 awk 命令比较字符串
【发布时间】:2015-06-15 18:20:16
【问题描述】:

我正处于学习 shell 脚本的初级阶段。所以请解释一下步骤以便更好地理解。

假设我有两个文件

这两个文件的内容如下:

文件1.txt

ABC=10
DEF=20
XYZ=30

文件2.txt

DEF=15
XYZ=20

我想编写一个简单的 shell 脚本来检查这两个文件并添加值并打印最终输出,如下所示。喜欢

ABC=10
DEF=35
XYZ=50

【问题讨论】:

    标签: bash shell awk


    【解决方案1】:

    你可以使用awk:

    awk 'BEGIN{FS=OFS="="} FNR==NR{a[$1]=$2;next} {a[$1]+=$2} 
         END{for (i in a) print i, a[i]}' file1 file2
    ABC=10
    XYZ=50
    DEF=35
    

    分手:

    NR == FNR {                  # While processing the first file
      a[$1] = $2                 # store the second field by the first in an array
      next                       # move to next record
    }
    {                            # while processing the second file
      a[$1]+=$2                  # add already stored value by 2nd field in 2nd file                                 
    }
    END{..}                      # iterate the array and print the values
    

    如果您想保持原始订单不变,请使用:

    awk 'BEGIN{FS=OFS="="} FNR==NR{if (!($1 in a)) b[++n]=$1; a[$1]=$2;next} {a[$1]+=$2}
         END{for (i=1; i<=n; i++) print b[i], a[b[i]]}' file1 file2
    ABC=10
    DEF=35
    XYZ=50
    

    【讨论】:

    • 感谢您回复我的问题,您能否详细解释一下,因为我对脚本/编程非常陌生..
    猜你喜欢
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    相关资源
    最近更新 更多