########################
1. shell的Pathname Expansion方式:
# *.txt先被shell解釋,替換成當前目錄下的所有*.txt
# awk對多文件的處理流程是,依次讀取各個文件內容,如上例,先讀a.txt,再讀b.txt....
在多文件處理的時候,如何對不同文件做不同的操作呢?
# 處理 2 個文件
########################
awk 'NR==FNR{...}NR>FNR{...}' file1 file2
或
awk 'NR==FNR{...}NR!=FNR{...}' file1 file2
FNR和NR這兩個awk內置變量的意義
FNR The input record number in the current input file. #已讀入當前文件的記錄數
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.
awk 'NR==FNR{...}NR>FNR{...}' file1 file2
# 讀入file1的時候,已讀入file1的記錄數FNR一定等於awk已讀入的總記錄數NR,因爲file1是awk讀入的首個文件,故讀入file1時執行前一個命令塊{...}
# 讀入file2的時候,已讀入的總記錄數NR一定>讀入file2的記錄數FNR,故讀入file2時執行後一個命令塊{...}
awk 'NR==FNR{...;next}{...}' file1 file2
# 讀入file1時,滿足NR==FNR,先執行前一個命令塊,但因爲其中有next命令,故後一個命令塊{...}是不會執行的
# 讀入file2時,不滿足NR==FNR,前一個命令塊{..}不會執行,只執行後一個命令塊{...}
# 處理 多個 文件
########################
# cat a
1:adf
2:adf
3:fds
4:vds
5:ldv
# cat b
a asd
b dfs
c sfd
d asd
e ldk
用b文件的第一個字段將a文件的第二個字段替換掉
# awk 'BEGIN{FS="[: ]+";OFS=":"}NR==FNR{a[k]=$1;k++;next}{print $1,a[i];i++}' b a
1:a
2:b
3:c
4:d
5:e
再加一文件c
# cat cone a234
two afd
three adsf
four adsf
five bsdf
將a,b,c三個文件的第一個字段提取出來,生成一個新文件
# awk 'BEGIN{FS="[: ]+";OFS=":"}ARGIND==1{a[i]=$1;i++;next}ARGIND==2{b[k]=$1;k++;next}{print a[v],b[n],$1;v++;n++}' a b c
1:a:one
2:b:two
3:c:three
4:d:four
5:e:five