AWK If / ElseConditional Problem
I have data that looks like this:
foo foo scaffold_7 1 4845 6422 4845
bar bar scaffold_7 -1 14689 16310 16310
What I want to do is process the above lines where I just want to print column 1,2,3,7 and one more column after the 7th. But with a condition when printing column 7 and onwards.
Below is my awk script:
awk '{
if ($4=="+") { {end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7 "\t" end+$7} }
else
{end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7}
}'
But why doesn't he achieve the desired result?
foo foo scaffold_7 1 4845 6422
bar bar scaffold_7 -1 14689 16310
Note that arithmetic (such as $7-end
or end+$7
) is required. Thus, we cannot simply replace the column from the input file. Also, this AWK will be inside the bash script.
source to share
Try:
awk 'BEGIN {OFS = "\t"} {
end = $6 - $5
if ($4 >= 0) {
print $1, $2, $3, $4, $7, end + $7
} else {
print $1, $2, $3, $4, $7 - end, $7
}
}'
I have never used curly braces within curly braces and prefer two colons delimiters for this purpose. I'm pretty sure the else clause is only bound to {end=$6-$5}
in your example and not to the copied elements. In this case, it {print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7}
will be executed for all lines.
source to share