使用awk命令比较字符串

时间:2015-06-12 14:31:08

标签: bash shell awk

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

考虑我有两个文件

两个文件的内容如下:

FILE1.TXT

ABC=10
DEF=20
XYZ=30

FILE2.TXT

DEF=15
XYZ=20

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

ABC=10
DEF=35
XYZ=50

1 个答案:

答案 0 :(得分:0)

您可以使用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