[root@21 opt]#cat a
张三|000001
李四|000002
[root@21 opt]#cat b
000001|10
000001|20
000002|30
000002|15
#################################
想要得到的结果是将用户名,帐号和金额在同一行打印出来,如下:
张三|000001|10
张三|000001|20
李四|000002|30
李四|000002|15
#############################################
用如下语句处理后,得到以上结果:
awk -F'|' 'NR==FNR{a[$2]=$0;next}{print a[$1] FS $2}' a b
解释:
awk -F'|' 'NR==FNR{a[$2]=$0;next}{print a[$1] FS $2}' a b
There is no BEGIN block, and FS="|" by -F'|' argument
start to first file 'a'
1. read file a line 1 and get data 张三|000001
A: $0=张三|000001
B: $1=张三
C: $2=000001
NR and FNR are the same equal to 1, and run NR=FNR block
NR==FNR{a[$2]=$0;next}
A: a[$2]=$0
a[000001]=张三|000001
B: next
next cycle and get next line data
2. read file a line 2 and get data 李四|000002
A: $0=李四|000002
B: $1=李四
C: $2=000002
NR and FNR are the same equal to 2, and run NR=FNR block
NR==FNR{a[$2]=$0;next}
A: a[$2]=$0
a[000002]=李四|000002
B: next
next cycle and get next line data
end of the file a, and get next file b data
3. read file b line 1, and get data 000001|10
A: $0=000001|10
B: $1=000001
C: $2=10
now, NR is 3 and FNR is 1, they are not eqaul
and didn't run NR=FNR block,
and run next block {print a[$1] FS $2}
a[$1] => a[000001] => 张三|000001
FS => |
$2 => 10
you will see the output
张三|000001|10
4. read file b line 2, and get data 000001|20
A: $0=000001|20
B: $1=000001
C: $2=20
NR is 4 and FNR is 2, they are not eqaul
and didn't run NR=FNR block,
and run next block {print a[$1] FS $2}
a[$1] => a[000001] => 张三|000001
FS => |
$2 => 20
you will see the output
张三|000001|20
cycle to read the file b
5. read file b line 3, and get data 000002|30
...
output==> 李四|000002|30
6. read file b line 4, and get data 000002|15
...
output==> 李四|000002|15
阅读(1506) | 评论(0) | 转发(0) |