Merge two files using awk in linux

前端 未结 2 1394
不思量自难忘°
不思量自难忘° 2021-01-25 01:45

I have a 1.txt file:

betomak@msn.com||o||0174686211||o||7880291304ca0404f4dac3dc205f1adf||o||Mario||o||Mario||o||Kawati
zizipi@libero.it||o||174732943.0174732943         


        
相关标签:
2条回答
  • 2021-01-25 02:06

    If your actual Input_file(s) are same as shown sample then following awk may help you in same.

    awk -v s1="||o||" '
    FNR==NR{
      a[$9]=$1 s1 $5;
      b[$9]=$13 s1 $17 s1 $21;
      next
    }
    ($1 in a){
      print a[$1] s1 $2 FS $3 s1 b[$1]
    }
    ' FS="|" 1.txt FS=":" 2.txt
    

    EDIT: Since OP has changed requirement a bit so providing code as per new ask where it will create 2 files too 1 file which will have ids present in 1.txt and NOT in 2.txt and other will be vice versa of it.

    awk -v s1="||o||" '
    FNR==NR{
      a[$9]=$1 s1 $5;
      b[$9]=$13 s1 $17 s1 $21;
      c[$9]=$0;
      next
    }
    ($1 in a){
      val=$1;
      $1="";
      sub(/:/,"");
      print a[val] s1 $0 s1 b[val];
      d[val]=$0;
      next
    }
    {
      print > "NOT_present_in_2.txt"
    }
    END{
    for(i in d){
      delete c[i]
    };
    for(j in c){
      print j,c[j] > "NOT_present_in_1.txt"
    }}
    ' FS="|" 1.txt FS=":" OFS=":" 2.txt
    
    0 讨论(0)
  • 2021-01-25 02:13

    You can use this awk to get your output:

    awk -F ':' 'NR==FNR{a[$1]=$2 FS $3; next} FNR==1{FS=OFS="||o||"; gsub(/[|]/, "\\\\&", FS)}
    $3 in a{$3=a[$3]; print}' file2 file1 > result.txt
    
    cat result.txt
    frankmel@hotmail.de||o||0174844404||o||demodemo:||o||Melanie||o||Melanie||o||Kiesel
    apoka-paris@hotmail.fr||o||0174847613||o||~~@!:/92\||o||Sihem||o||Sihem||o||Sousou
    sofianomovic@msn.fr||o||174902297.0174902297||o||134:@a1||o||Nabile||o||Nabile||o||Nassime
    
    0 讨论(0)
提交回复
热议问题