In a row, replace negative sign and find minimum value among four columns

Hi Friends,

I have an input file like this

chr1 100 200 1 2 3 4
chr1 150 200 4 5 6 7
chr2 300 400 9 6 7 1
chr2 300 410 -10 21 -11 13
chr3 700 900 -21 -22 130 165

Now, my output file is

chr1 100 200 1
chr1 150 200 4
chr2 300 400 1
chr2 300 410 10
chr3 700 900 21

Remove negative signs from columns 4,5,6 and7 and then find the minimum value among these 4 columns for a row, and print the minimum value.

Thanks in advance.

Try:

awk '{for (i=4;i<=NF;i++) {if ($i<0) $i*=-1; $4=($i<$4)?$i:$4} print $1,$2,$3,$4}' file
1 Like
awk 'min="x" {for (i=4; i<=NF; i++) min=(min>$i)?$i:min} {print $1,$2,$3,sqrt(min*min)}' infile
1 Like

Always 7 fields? bash has trinary operator ?:

while read x y z a b c d
do
 (( a = a < 0 ? 0 - a : a ))
 (( b = b < 0 ? 0 - b : b ))
 (( c = c < 0 ? 0 - c : c ))
 (( d = d < 0 ? 0 - d : d ))
 (( m = a > b ? b : a ))
 (( m = m > c ? c : m ))
 (( m = m > d ? d : m ))
 echo $x $y $z $m
done < in_file

No multiply or sqrt. Could nest the last three. "tr -d '-' |" would remove the negatives in the string space.

1 Like

try also (based on bartus11 solution):

awk '{for (i=4;i<=NF;i++) {$i*=$i>0?1:-1; $4=$i<$4?$i:$4}} NF=4' infile

Shouldn't you start with 5, as 4 is neve less than 4?

0-$i save a multiply.

(Easier to criticize that to create! Slowly learning awk by osmosis!)