Sort the contents of a file using a String value in a specific sequence

I had the contents of the file confused as follows:

13,13,GAME_FINISH,
1,1,GAME_START,
1,1,GROUP_FINISH,
17,17,WAGER,200.00
2,2,GAME_FINISH,
2,2,GAME_START,
22,22,GAME_WIN,290.00
2,2,GROUP_FINISH,
32,32,WAGER,200.00
3,3,GAME_FINISH,
3,3,GAME_START,
.... more lines

I sorted it and am currently storing the contents of the file in the following format:

1,1,GAME_FINISH,
1,1,GAME_START,
1,1,GROUP_FINISH,
1,1,WAGER,200.00
2,2,GAME_FINISH,
2,2,GAME_START,
2,2,GAME_WIN,290.00
2,2,GROUP_FINISH,
2,2,WAGER,200.00
3,3,GAME_FINISH,
3,3,GAME_START,
3,3,GROUP_FINISH,
3,3,WAGER,200.00
... more lines

But how can I sort it better to get the following format? 3rd and 4th lines may not always exist.

1,1,WAGER,200.00
1,1,GAME_START,
1,1,GAME_WIN,500.00
1,1,BONUS_WIN_1,1100.00
1,1,GAME_FINISH,
1,1,GROUP_FINISH,
2,2, more lines...

For initial sorting, I used

sort -t, -g -k2 nameofunsortedfile.csv >> sortedfile.csv

Information added:

I want to sort it in this order - Wager, start of the game, win in the game, win in the bonus, game final, group final. My current order is not in that order. Winning a game and a bonus win may not always be present.

, , , . , , game_finish group_finish. game_win, game_bonus . , , 1,1 , 2,2 .

+4
2

UNIX - , , , , , .

declare -A mapping=( ["WAGER"]=1 ["GAME_START"]=2 ["GAME_WIN"]=3 ["BONUS_WIN"]=4 ["GAME_FINISH"]=5 ["GROUP_FINISH"]=6 )
cut -d, -f3 filename.txt | while read; do echo ${mapping["$REPLY"]}; done | paste -d, - filename.txt | sort | sort -s -t, -n -k 2,3 | cut -d, -f 2-

declare , . (1, 2 ..) , ; , .

:

  • cut -d, -f3 filename.txt , (WAGER - )
  • while read; do echo ${mapping["$REPLY"]}; done (WAGER ..) mapping
  • paste -d, - filename.txt filename.txt
  • sort | sort -s -t, -n -k 2,3 2, 3, 1 (, ). sort , sort, .
  • cut -d, -f 2- , ,
+2

:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my $i = 1;
my %order = map { $_ => $i++ }
            qw( WAGER GAME_START GAME_WIN BONUS_WIN GAME_FINISH GROUP_FINISH );

chomp( my @lines = <> );
say join ',', @$_ for sort {
    $a->[0] <=> $b->[0]
    || $order{ $a->[2] } <=> $order{ $b->[2] }
} map [ split /,/ ], @lines;

sort Perl , , "order" " .

+1

Source: https://habr.com/ru/post/1666548/


All Articles