12

I have a file that looks something like this:

ID101     G    T     freq=.5     nonetype     ANC=.1     addinfor
ID102     A    T     freq=.3     ANC=.01    addinfor
ID102     A    T     freq=.01     type=1     ALT=0.022    ANC=.02    addinfor

As you can see, each line has a slightly different number of columns. I specifically want column 1, column 2, column 3, column 4 and the column that starts with ANC=

Desired output:

ID101     G    T     freq=.5     ANC=.1
ID102     A    T     freq=.3     ANC=.01
ID102     A    T     freq=.01    ANC=.02

I generally use the an awk command to parse files:

awk 'BEGIN {OFS = "\t"} {print $1, $2, $3, $4}'

Is there an easy way to alter this command to work for situations like this?

I think something like this might work:

awk '{for(j=1;j<=NF;j++){if($j~/^ANC=/){print $j}}}'

However, how can I edit this to also print the first columns?

3 Answers 3

17

With awk:

awk '{for(i=5;i<=NF;i++){if($i~/^ANC=/){a=$i}} print $1,$2,$3,$4,a}' file

  • for(...) loops through all fields, starting with field 5 (i=5).
    • if($i~/^ANC=/) checks if the field starts with ANC=
    • a=$i if yes, set variable a to that value
  • print $1,$2,$3,$4,a print fields 1-4 followed by whatever is stored in a.

Can be combined with BEGIN {OFS="\t"} of course.

2
  • what does the i=5 do? Aug 23, 2016 at 12:31
  • @stellar01 this starts the loop at field number 5.
    – chaos
    Aug 23, 2016 at 12:33
0

Assuming that the ANC= column is always the second-to-last column (as in the example data):

$ awk '{ print $1, $2, $3, $(NF-1) }' data.in
ID101 G T ANC=.1
ID102 A T ANC=.01
ID102 A T ANC=.02

NF is the number of fields (columns) that awk splits each record (line) into. $(NF-1) is the value of the second-to-last field.

0
perl -pale '$"="\t", $_="@{[@F[0..3],         grep {   /^ANC=/ } @F[4..$#F]]}"' yourfile
perl -lane '$,="\t",          print @F[0..3], grep {   /^ANC=/ } @F[4..$#F]'    yourfile
perl -lane '($,,$a)=("\t",0), print grep { $a++ < 4 or /^ANC=/ } @F'            yourfile

Brief

$, => OFS @F[0..3] => $F[0] $F[1] $F[2] $F[4]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .