一、概念解析
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{...}”第二個循環,列印輸出指令結果。
(1)一種是
awk 'NR==FNR{...}NR>FNR{...}' file1 file2 或 awk 'NR==FNR{...}NR!=FNR{...}' file1 file2
(2) 另一種是
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.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.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
本文轉自 pgmia 51CTO部落格,原文連結:http://blog.51cto.com/heyiyi/1270688