- 论坛徽章:
- 145
|
回复 1# 123498296
How about below:
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
|
|