0

I have a file of multiple columns. I would like to make an additional column based on the values of 2 columns from this file.

Example input:

A B C D E F
1 2 T TACA A 3 2
3 4 I R 8 2
9 3 A C 9 3
  1. If the values in cols 3 and 4 (labelled C and D) are the letters A,C,G or T, col 7 should be P.
  2. If the letters in cols 3 and 4 are I, D, or R, col 7 should be Q.
  3. If there are multiple letters in either column 3 or 4, col 7 should be Q.

Desired ouput:

A B C D E F G
1 2 T TACA A 3 2 Q
3 4 I R 8 2 Q
9 3 A C 9 3 P

I have the following code except this replaces some of the col 3 values with '1'. I want to leave cols 1-6 unchanged.

awk '{if ((($3!="A" && $3!="C" && $3!="G" && $3!="T") || ($3="I" || $3="D" || $3="R")) || (($4!="A" && $4!="C" && $4!="G" && $4!="T") || ($4="I" || $4="D" || $4="R"))) { $7 = "INDEL" } else { $7 = "SNP" }}1' filename > newfilename
2

This works with mawk:

awk 'NR==1{$7="G";print;next} \
  $3~/^[A,C,G,T]$/ || $4~/^[A,C,G,T]$/ {$7="P"} \
  $3~/^[I,D,R]$/ || $4~/^[I,D,R]$/ {$7="Q"} \
  $4~/[A-Z][A-Z]/ || $3~/[A-Z][A-Z]/ {$7="Q"} 1' file
  1. line: In the first line write the G in the header.
  2. line: If $3 of $4 are A, C, G or T then $7 is P.
  3. line: If $3 of $4 are I, D, or R then $7 is Q.
  4. line: If $3 of $4 are more than one Letter then $7 is Q. The 1 at the end prints all lines.
  • The $3 and $4 have same rules so you can attach it for shortening awk '$3$4~/[A-Z]{3,}/||$3$4~/^[IDR]{2}$/{$7="Q"}$3$4~/^[ACGT]{2}$/{$7="P"}1' file – Costas Aug 26 '15 at 12:24
0

This code is self explanatory and easy to understand. You may change the last else condition as per your requirement or you may ignore it as well. Let's say we have input file named as "input_file.txt" and we create an awk prog into another file named as "XXXX.awk" . Now run it on command line using

awk -f XXXX.awk input_file.txt

    BEGIN { 
       FS=" ";
    }
    {
        if(NR==1) print $0" G";
        else if(length($4)>1 || length($3)>1) print $0" Q";
        else if($3 ~ /[I,D,R]/ && $4 ~ /[I,D,R]/) print $0" Q";
        else if($3 ~ /[A,C,G,T]/ && $4 ~ /[A,C,G,T]/) print $0" P";
        else print $0" NA";
    }
  • are you sure about regexp syntax ? I would have wrote /IDR/ and /ACGT/ – Archemar Oct 28 '17 at 8:34
  • Yes using "character set", you can tell the regex engine to match only one out of several characters. If you go for /IDR/ then it will not match single character instead it will look for "IDR" as complete string. Note: You may remove commas also in character set [I,D,R] – Abhishek Dangarh Oct 28 '17 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.