使用awk处理具有不同字段分隔符的2个文件 [英] Processing 2 files with different field separators using awk
本文介绍了使用awk处理具有不同字段分隔符的2个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有2个文件:
$ cat file1
A:10
B:5
C:12
$ cat file2
100 A
50 B
42 C
我想要类似的东西:
A 10 100
B 5 50
C 12 42
我尝试过这个:
awk 'BEGIN{FS=":"}NR==FNR{a[$1]=$2;next}{FS=" ";print $2,a[$2],$1}' file1 file2
哪个输出给我:
100 A
B 5 50
C 12 42
我猜问题出在字段分隔符,它对于第二个文件设置得太晚了.如何为不同的文件(而不是单个文件)设置不同的字段分隔符?
I guess the problem comes from the Field Separator which is set too late for the second file. How can I set different field separator for different files (and not for a single file) ?
谢谢
更一般的情况
使用file2和file3像这样:
With file2 and file3 like this :
$ cat file3
A:10 foo
B:5 bar
C:12 baz
如何获取:
A 10 foo 100
B 5 bar 50
C 12 baz 42
推荐答案
只需在文件之间设置FS:
Just set FS between files:
awk '...' FS=":" file1 FS=" " file2
即:
$ awk 'NR==FNR{a[$1]=$2;next}{print $2,a[$2],$1}' FS=":" file1 FS=" " file2
A 10 100
B 5 50
C 12 42
这篇关于使用awk处理具有不同字段分隔符的2个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文