Home > front end >  Apply multiple substract commands between two columns in text file in bash
Apply multiple substract commands between two columns in text file in bash

Time:11-30

I would like to substract 2x two columns in a text file and add into two new columns in a tab delimited text file in bash using awk.

  1. I would like to substract column 3 (h3) - column 1 (h1). And name the new added column "count1".
  2. I would like to substract column 4 (h4) - column 2 (h2). And name the new added column "count2".

I don't want to build a new text file, but edit the old one.

My text file:

    h1 h2 h3 h4 h5    
    343 100 856 216 536
    283 96 858 220 539
    346 111 858 220 539
    283 89 860 220 540
    280 89 862 220 541
    76 32 860 220 540
    352 105 856 220 538
    57 16 860 220 540
    144 31 858 220 539
    222 63 860 220 540
    305 81 858 220 539

My command at the moment looks like this:

awk '{$6 = $3 - $1}1' file.txt
awk '{$6 = $4 - $2}1' file.txt

But I don't know how to rename the new added columns and maybe there is a smarter move to run both commands in the same awk command?

CodePudding user response:

Pretty simple in awk. Use NR==1 to modify the first line.

awk -F '\t' -v OFS='\t' '
NR==1 {print $0,"count1","count2"}
NR!=1 {print $0,$3-$1,$4-$2}' file.txt > tmp && mv tmp file.txt
  •  Tags:  
  • bash
  • Related