Print rows in reverse order if values decrease along the column

Hi, Guys. Please help me to find solution to this problem using shell scripting.

I have an INPUT file with 4 columns separated by tab. Each block of records is separated by -----

-----
Sample1      5402        6680          Pattern01
Sample2      2216        2368          Pattern02
Sample3      1932        2122          Pattern09
-----
Sample1      75209        76057        Pattern05
Sample2      76269        76713        Pattern01
Sample3      82346        82510        Pattern07
Sample4      82606        82796        Pattern06
-----
sample1      41587        44548        Pattern90
-----

I need to print rows in reverse order if values decrease along the column in a particular Block and to print the Block as it is if there is a single record or the column values are in increasing order.

Required OUTPUT is :

-----
Sample3      1932        2122          Pattern09
Sample2      2216        2368          Pattern02
Sample1      5402        6680          Pattern01
-----
Sample1      75209        76057        Pattern05
Sample2      76269        76713        Pattern01
Sample3      82346        82510        Pattern07
Sample4      82606        82796        Pattern06
-----
sample1      41587        44548        Pattern90
-----

Thanks in advance.

Use the following command

sort -k 3 input_file

Here input_file will contain your data.
According to the 3rd column value it will sort the rows.

 awk '{if ($0~/^-/) {print $0 ORS b;a=0;b=""}
      else {if ($2>a) {b=b ORS $0}
            else {b=$0 ORS b}
            {a=$2}
            }
     }' INPUT |grep -v ^$

Thanks Selwan and rdcwayx. Athough sorting on the 3rd column will not sort within blocks of data but awk code is working fine. Thanks again :slight_smile:

---------- Post updated at 01:21 PM ---------- Previous update was at 12:20 PM ----------

Hi, how can I do the reverse that is print all the rows in decreasing order values in each Block?

local $/="-----\n";
while(<DATA>){
	s/-----//;
	if($_ ne "\n" ){
		my @tmp=split("\n",$_);
	  print "-----\n";
		print join "\n", map {$_->[0]} sort {$a->[1]<=>$b->[1]} map {my @t=split; [$_,$t[1]]} @tmp;
		print "\n";
	}
}
__DATA__
-----
Sample1      5402        6680          Pattern01
Sample2      2216        2368          Pattern02
Sample3      1932        2122          Pattern09
-----
Sample1      75209        76057        Pattern05
Sample2      76269        76713        Pattern01
Sample3      82346        82510        Pattern07
Sample4      82606        82796        Pattern06
-----
sample1      41587        44548        Pattern90
-----

Another one in perl,

perl -lane 'if (/^-/) { foreach (sort keys(%h)) { print "$h{$_}";  } %h=();print; } else { $h{$F[1]}=$_; }' file

and the reverse sort,

perl -lane 'if (/^-/) { foreach (reverse sort keys(%h)) { print "$h{$_}";  } %h=();print; } else { $h{$F[1]}=$_; }' file

Thanks summer cherry and Thanks Dennis.