AWK 两个文件字段合并处理实例

一、概念解析

1、awk命令概念

$0 表示一个文本中的一行记录

$1...N 表示一行中的第 1...N 字段

FNR     The input record number in the current input file.  #已读入当前文件的记录数

NR      The total number of input records seen so far.      #已读入的总记录数

next    Stop processing the current input record. The next input record is

       read and processing starts over with the first pattern in the AWK

       program. If the end of the input data is reached, the END block(s),

       if any, are executed.

2、处理两个文本文件

执行处理顺序:

首先,对file1执行“NR==FNR{…}”第一个循环,建立哈希数组;第二步,执行“NR>FNR{…}”第二个循环,打印输出命令结果。

  • 一种是
awk 'NR==FNR{...}NR>FNR{...}' file1 file2 或 awk 'NR==FNR{...}NR!=FNR{...}' file1 file2
  • 另一种是
awk 'NR==FNR{...;next}{...}' file1 file2

二、处理两个文件实例

1、处理实例一

file1:

文件内容:

sina.com 52.5

sohu.com 42.5

baidu.com 35

file 2:

文件内容:

www.news.sina.com sina.com 80

www.over.sohu.com baidu.com 20

www.fa.baidu.com sohu.com 50

www.open.sina.com sina.com 60

www.sport.sohu.com sohu.com 70

www.xxx.sohu.com sohu.com 30

www.abc.sina.com sina.com 10

www.fa.baidu.com baidu.com 50

www.open.sina.com sina.com 60

www.over.sohu.com sohu.com 20


awk 'NR==FNR{a[$1]=$2;next}{print $0,a[$2]}' f1 f2

命令结果:

www.news.sina.com sina.com 80 52.5

www.over.sohu.com baidu.com 20 35

www.fa.baidu.com sohu.com 50 42.5

www.open.sina.com sina.com 60 52.5

www.sport.sohu.com sohu.com 70 42.5

www.xxx.sohu.com sohu.com 30 42.5

www.abc.sina.com sina.com 10 52.5

www.fa.baidu.com baidu.com 50 35

www.open.sina.com sina.com 60 52.5

www.over.sohu.com sohu.com 20 42.5

2、处理实例二

需要处理的同名字段可以在两个文件中行号不同的行,无需行号排序相对应,

命令结果的行顺序依据第二个文件中同名字段顺序输出。

f1

文件内容:

10020036 beijing

10050259 lanzhou

10045682 hefei

20130495 guangzhou

20981345 shenzhen

20984748 chengdu

20891376 changsha

f2

文件内容:

guangzhou 4.5

hefei 2.6

beijing 1.3

shenzhen 8.5

changsha 0.8

chengdu 2.0

lanzhou 2.4


awk 'NR==FNR{a[$2]=$1}NR>FNR{print a[$1],$0}' f1 f2

命令输出:

20130495 guangzhou 4.5

10045682 hefei 2.6

10020036 beijing 1.3

20981345 shenzhen 8.5

20891376 changsha 0.8

20984748 chengdu 2.0

10050259 lanzhou 2.4
发布于:2019-11-13 10:49:57