########################
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