LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash regex - sort (https://www.linuxquestions.org/questions/programming-9/bash-regex-sort-702568/)

czezz 02-05-2009 03:36 PM

bash regex - sort
 
Here is a sample of a file.
File is divided into a section called: case "some_number"
As you can see numbers are set randomly.
What I need to achive is to sort all case sections beginning from the lowest to highest, so case "4" is 1st; case "111" is 2nd and case "309" is 3rd.

The problem is that content of each case sections must be kept.
Is this possible ?


Code:

case "309": ### - asdasdscxczx
      @string_1 = "irgoirhgoi;rhgv;rhg;rdsh;sdhfkjdsbhjbdjsv"
      @string_2 = @Mafda + @Aasdant + @asdsas
      string_3($*) # #$lslslslslsr,$psdfdsfgsdfdsfdste
      $string_4

case "4": ### - fgvbfdvcxvcx
      @string_1 = "asdsadefesdvfgwegfvrds"
      @string_2 = @ssfMsdfdsa + @asdsadsant + @dfdsgrgrv
      string_3($*) # #$asdfdsafsadsaadwfcedsfefcerc
      $string_4

case "111": ### - fgfb vrdsadsadxca
      @string_1 = "irgoirhgoi;rhgv;rhg;rdsh;sdhfkjdsbhjbdjsv"
      @string_2 = @Mafda + @Aasdant + @asdsas
      string_3($*) # #sadsdsadslslsr,$pasdasdsasdsxa
      $string_4


theNbomr 02-05-2009 04:19 PM

Not a bash solution, but that is the wrong hammer for this kind of nail.
Code:

#! /usr/bin/perl -w
# -------- LQczezz.pl -----------
use strict;
$/ = "\n\n";
    my @wholeFile = <>;
    foreach my $case ( sort byCaseNumber @wholeFile ){   
        print $case;
    }

sub byCaseNumber{
    $a =~ m/case\s+"(\d+)"/;
    my $caseNumA = $1;
    $b =~ m/case\s+"(\d+)"/;
    my $caseNumB = $1;
    if( $caseNumA > $caseNumB ){ return 1; }
    if( $caseNumA < $caseNumB ){ return -1; }
    return 0;
}

Run with sample file as commandline argument.
--- rod.

czezz 02-05-2009 04:42 PM

Well... I must say I like that hammer :)
Many thanks.

Telemachos 02-05-2009 07:41 PM

The OP has a good answer, but I was thinking about this post on the subway ride home before I saw the answer. So in the spirit of TIMTOWTDI, here's my variant on it:
Code:

#!/usr/bin/env perl
use warnings;
use strict;

my @blocks = do { local $/ = "\n\n"; <> };

@blocks = sort { get_num($a) <=> get_num($b) } @blocks;

print @blocks;

sub get_num{
  my $item = shift;
  $item =~ m/case "(\d+)"/;
  return $1;
}



All times are GMT -5. The time now is 10:14 PM.