Processing 2 files with different field separators using awk

前端 未结 3 648
孤独总比滥情好
孤独总比滥情好 2020-12-15 14:15

Let\'s say I have 2 files :

$ cat file1
A:10
B:5
C:12

$ cat file2
100 A
50 B
42 C

I\'d like to have something like :

A 10          


        
相关标签:
3条回答
  • 2020-12-15 14:27

    You can try something like:

    $ cat f1
    A:10
    B:5
    C:12
    

    $  cat f2
    100 A
    50 B
    42 C
    

    $ awk 'NR==FNR{split($0,tmp,/:/);a[tmp[1]]=tmp[2];next}$2 in a{print $2,a[$2],$1}' f1 f2
    A 10 100
    B 5 50
    C 12 42
    

    or set multiple field separators

    $ awk -F"[: ]" 'NR==FNR{a[$1]=$2;next}$2 in a{print $2,a[$2],$1}' f1 f2
    A 10 100
    B 5 50
    C 12 42
    
    0 讨论(0)
  • 2020-12-15 14:44

    Just set FS between files:

    awk '...' FS=":" file1 FS=" " file2
    

    i.e.:

    $ 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
    
    0 讨论(0)
  • 2020-12-15 14:45

    You need to get awk to re-split $0 after you change FS.

    You can do that with $0=$0 (for example).

    So {FS=" ";$0=$0;...} in your final block will do what you want.

    Though only doing that the first time you need to change FS will likely perform slightly better for large files.

    0 讨论(0)
提交回复
热议问题