Bot75
Bot75

Reputation: 169

field separator in awk

I have the following "input.file":

10      61694   rs546443136     T       G       .       PASS    RefPanelAF=0.0288539;AC=0;AN=1186;INFO=1.24991e-09      GT:DS:GP        0/0:0.1:0.9025,0.095,0.0025     0/0:0.1:0.9025,0.095,0.0025     0/0:0.1:0.9025,0.095,0.0025

My desired output.file is:

0.1, 0.1, 0.1

Using an awk script called "parse.awk":

BEGIN {FS = ":"}
{for (i = 4; i <= NF; i += 2) printf ("%s%c", $i, i +2 <= NF ? "," : "\n ");}

which is invocated with:

awk -f parse.awk <input.file >output.file

my current output.file is as follows:

0.1,0.1,0.1

i.e. no spaces.

Changing pasre.awk to:

BEGIN {FS = ":"}
{for (i = 4; i <= NF; i += 2) printf ("%s%c", $i, i +2 <= NF ? ", " : "\n ");}

did not change the output.file. What change(s) to parse.awk will yield the desired output.file?

Upvotes: 2

Views: 94

Answers (3)

Hai Vu
Hai Vu

Reputation: 40803

The problem is when you changed the output separator from a single comma (",") to comma with space (", "); you did not change the format string from %c to %s. So that is how to fix your script:

BEGIN {FS = ":"}
{for (i = 4; i <= NF; i += 2) printf ("%s%s", $i, i +2 <= NF ? ", " : "\n ");}
#                                         ^ Change this

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133780

Could you please try following. Written and tested it in https://ideone.com/e26q7u

awk '
BEGIN {FS = ":"}
val!=""{ print val; val=""}
{for (i = 4; i <= NF; i += 2){
  val=(val==""?"":val", ")$i
  }
}
END{
  if(val!=""){
    print val
  }
}
' Input_file

Upvotes: 3

anubhava
anubhava

Reputation: 786359

You may use this awk:

awk -F: -v OFS=', ' '{
  for (i = 4; i <= NF; i += 2) printf "%s%s", $i, (i < NF-1 ? OFS : ORS)}' file
0.1, 0.1, 0.1

Upvotes: 3

Related Questions