justaguy
justaguy

Reputation: 3022

awk to insert value and remove field

Trying to use awk to insert a value into $4 based of a pattern in $5, then remove $5. $4 already has a value in it I am trying to insert the new value in front of it with a : between the two values. The awk does execute but not as expected. Thank you :).

f tab-delimited

chr1    629031  GT:CN   4   High Copy Gain
chr1    632301  GT:CN   3   CN Gain
chr1    6440431 GT:CN   2   CN Loss
chr1    16691021    GT:CN   1   Homozygous Copy Loss
chr1    6440431 GT:CN   0   CN Loss

awk

awk -F'\t' '{if ( $5~ /CN/ ) {print $4 ":" "0/1"} else {print $ ":" "1/1"}}' OFS="\t" f.txt | awk -F'\t' '!($5="")'

current tab-delimited

chr1 629031 GT:CN 4
3:0/1
2:0/1
chr1 16691021 GT:CN 1
0:0/1

desired tab-delimited

chr1    629031  GT:CN   1/1:4
chr1    632301  GT:CN   0/1:3
chr1    6440431 GT:CN   0/1:2
chr1    16691021    GT:CN   1/1:1
chr1    6440431 GT:CN    0/1:0

Upvotes: 1

Views: 36

Answers (3)

vgersh99
vgersh99

Reputation: 945

$ awk -F'\t' '{$4=(($5~/CN/)?0:1)"/1:"$4}NF--' OFS='\t' myFile
chr1    629031  GT:CN   1/1:4
chr1    632301  GT:CN   0/1:3
chr1    6440431 GT:CN   0/1:2
chr1    16691021        GT:CN   1/1:1
chr1    6440431 GT:CN   0/1:0

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You may try this awk:

awk 'BEGIN {FS=OFS="\t"} {$4 = ($5 ~ /^CN/ ? "0/1:" : "1/1:") $4; sub(/\t[^\t]+$/, "")} 1' f.txt | column -t

chr1  629031    GT:CN  1/1:4
chr1  632301    GT:CN  0/1:3
chr1  6440431   GT:CN  0/1:2
chr1  16691021  GT:CN  1/1:1
chr1  6440431   GT:CN  0/1:0

Expanded awk:

awk 'BEGIN {
   FS = OFS = "\t"
} {
   $4 = ($5 ~ /^CN/ ? "0/1:" : "1/1:") $4
   sub(/\t[^\t]+$/, "")
} 1' f.txt |
column -t

Upvotes: 1

karakfa
karakfa

Reputation: 67467

you have a typo and using print instead of modifying the field,

$ awk 'BEGIN{FS=OFS="\t"} {$4=(($5~/CN/)?"0":"1")"/1:"$4; $5=""}1' file

should do what you're trying to do.

Can be further simplified to

$ awk 'BEGIN{FS=OFS="\t"} {$4=($5!~/CN/)"/1:"$4; $5=""}1' file

Upvotes: 1

Related Questions