0
5500 5700
5600 5800
5700 5800
5600 5900
5900 6100
5900 6100
5900 6100
5800 6000
5800 6100
5900 6100
5800 6200
5700 5800

I have a file with two columns as above. I need to find out min of every two rows in the first column and max of every two rows in the second column.How can it be achieved using awk? Desired output would be

Min      Max
5500     5800
5600     5900
5900     6100
5800     6100
5800     6100
5700     6200  
  • 1
    Can you please add what do you expect as output and clarify what do you mean by "every two rows"? – Romeo Ninov May 16 '17 at 8:47
  • In the first column for the first two row compare first 5500 and 5600 and get 5500 (Min), and in the second column compare first 5700 and 5800 and get 5800 (Max). And so forth. – firefoxix May 16 '17 at 8:51
  • So you need minimum from 1st row and maximum from second row? But after do you go to 3th and 4th or 2nd and 3th? – Romeo Ninov May 16 '17 at 8:53
  • Not so. Take two rows from first column and find min of that. Same for second column but for max. Thereafter take two more rows and find out Min and Max for these and so on. – firefoxix May 16 '17 at 8:57
  • Please edit your question and show us your desired output. As you can see, your question is not very clear without it. – terdon May 16 '17 at 8:58
1
$ awk 'BEGIN { print "Min", "Max" } {a=$1; b=$2; getline; print ($1<a?$1:a), ($2>b?$2:b)}' data.in
Min Max
5500 5800
5600 5900
5900 6100
5800 6100
5800 6100
5700 6200

The awk code saves the current values in column one and two into the variables a and b respectively. It then reads the next line explicitly and prints the minimum of a and the new value in column one together with the maximum of b and the new value of column two.

($1 < a ? $1 : a) is using the ternary operator ?: to make a comparison and choose a value depending on the outcome of that comparison.

If you want tab-delimited output:

$ awk 'BEGIN {OFS="\t"; print "Min", "Max"} {a=$1; b=$2; getline; print ($1<a?$1:a), ($2>b?$2:b)}' data.in
Min     Max
5500    5800
5600    5900
5900    6100
5800    6100
5800    6100
5700    6200
  • Thank you for quick answer an d explanation. This solves my problem. – firefoxix May 16 '17 at 9:31
0
perl -pe '($_ .= <>) =~ s/(\d+) (\d+)\n(\d+) (\d+)/($3<$1 ? $3:$1).$".($4>$2 ? $4:$2)/e'

Append next line into the current record $_ and then compare field 3<->1 for min and 4<->2 for max and put the results within the record itself. -p will carry the result to stdout after that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.