Prasoon Agarwal
Prasoon Agarwal

Reputation: 7

use of AWK for obtaining non negative value

I am trying to make my second column as non negative as some of the values are positive and some negative, so trying AWK function.

I have six columns in my bed file I am using the following command

awk -F"\t"  '{print $1"\t"$2<0?$2*-1:$2"\t"$3"\t"$4"\t"$5"\t"$6}' CTCF_first_coordinates > CTCF_first_coordinates_new

My problem is when I run this, then my first column is not printed and the values are not converted to non negative. However if i don't print my first column the code works.

Can anybody suggest how can I improve my code to get the proper output?

Below is the input bed file which is tab delimited and second column contain negative values together with positive values

chr18 576980 586980 CETN1 CLUL1 M1 
chr18 -8280 1720 NA USP14 M1

and the output i need is below where I want the negative value to be positive and rest everything remains same

chr18 576980 586980 CETN1 CLUL1 M1 
chr18 8280 1720 NA USP14 M1

In addition to the above problem I have some more issue where the output file as shown above the first coordinate is larger than the second coordinate. Is there any method to interchange the selected values of the two columns in the file i.e column 2 and 3. I have 192 such instances in the whole file. So my output should be something like

chr18 576980 586980 CETN1 CLUL1 M1 chr18 1720 8280 NA USP14 M1

Upvotes: 0

Views: 521

Answers (1)

fedorqui
fedorqui

Reputation: 290025

Just change the sign if it is negative:

$ awk '$2<0 {$2=-$2}1' file
chr18 576980 586980 CETN1 CLUL1 M1 
chr18 8280 1720 NA USP14 M1

The 1 at the end of the command is a way to set something to True in awk, so that it performs its default behaviour: print the current line.

Upvotes: 0

Related Questions