how to use awk to do subtraction with numbers in a large file

5,739

awk 'BEGIN { FS=OFS="," } {print $0,$5-$3,$6-$3}' my_file

Share:
5,739

Related videos on Youtube

Érik Freitas
Author by

Érik Freitas

I CODE

Updated on September 18, 2022

Comments

  • Érik Freitas
    Érik Freitas over 1 year

    I have a large file like this

    AT5G44030,TAACARA,1000,+,200,206
    AT5G44030,TAACARA,1000,+,418,424
    AT5G44030,TAACARA,1000,+,773,779
    AT5G44030,NGATT,1000,+,114,118
    AT5G44030,NGATT,1000,+,267,271
    ....................................
    

    I want to add two columns at the end with subtractions of 5th - 3rd , 6th - 3rd so the final file should look like follows.

    AT5G44030,TAACARA,1000,+,200,206,-800,-794
    AT5G44030,TAACARA,1000,+,418,424,-582,-576
    AT5G44030,TAACARA,1000,+,773,779,-227,-221
    AT5G44030,NGATT,1000,+,114,118,-886,-882
    AT5G44030,NGATT,1000,+,267,271,-733,-729
    
    .......................................
    

    (note that there are no empty lines in between)

    How do I do this using awk or sed ? The file is very large -- 1M lines.

  • Alessio
    Alessio about 8 years
    or set OFS="," to avoid having to manually add "," between each new field: awk 'BEGIN { FS=","; OFS=","} {print $0, $5-$3, $6-$3}'