1

In the awk below I am trying to add adjust $2 in the ouput by adding +1 if the original value from file that was used in $2 had a - in it. Line 2 of in is an example of this. In my current awk I my logic is not correct as I am looking in $2 and splitting on the - and storing the values in 'array' if there is one and keeping the count of the fields in num. Based on the count in num I print the output of the split or no split. In my actual data there may be hundreds of lines but always the same format. Seems close but not quite there. Thank you :).

in

chr15 91543131 AAW33B
chr8 100493900-100493909 SBSA

awk

awk '{num=split($2,array,"[ -]");if(num==3){print $1,$2-1,$2,$3};if(num==4){print $1,array[1],array[2],array[2],$3}}' in | column -t

desired tab-delimited

chr15   91543130    91543131    AAW33B
chr8    100493900   100493909   SBSA
7
  • 1
    What is your actual input? Do you have --- or just -? Is the --- num==3??? --- part of your input?
    – terdon
    May 15, 2019 at 15:32
  • 1
    it seems to me that you created a new field on line one since it did not contain a dash; you also split line two based on the dash?
    – Jeff Schaller
    May 15, 2019 at 15:38
  • 1
    If your input is space-delimited, you could set FS to /[ -]/ and then look at NF to determine what your output should be.
    – DopeGhoti
    May 15, 2019 at 15:39
  • 1
    Please edit your question and show us the exact input you are trying to parse. It looks like you want to produce a bed file, starting from some sort of weird vcf-like format, but I can't tell if you don't show us actual lines from the file.
    – terdon
    May 15, 2019 at 15:47
  • 1
    You might be interested in our sister site, Bioinformatics.
    – terdon
    May 15, 2019 at 16:18

1 Answer 1

2

Given this input:

chr15 91543131 AAW33B
chr8 100493900-100493909 SBSA

We can simply have awk split input based on /[ -]/ (i. e. a space or a - as a field separator). We can also just give awk a tab as an output field separator which means we no longer need column -t:

$ awk 'BEGIN { FS = "[ -]"; OFS="\t" } NF==3 { print $1, $2 - 1, $2, $3 } NF==4 { print $1, $2, $3, $4 }' input
chr15   91543130    91543131    AAW33B
chr8    100493900   100493909   SBSA

Alternatively, we could leave the field separator alone, and just look to see whether the second field contains a -:

$ awk 'BEGIN { OFS="\t" } $2 !~ /-/ { print $1, $2 - 1, $2, $3 } $2 ~ /-/ { split( $2, a, "-" ); print $1, a[1], a[2], $3 }' input
chr15   91543130    91543131    AAW33B
chr8    100493900   100493909   SBSA
0

You must log in to answer this question.

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