-1

I would like to reorder a whole file.

file.txt looks like this:

1 10
1 10
2 10
1 11
2 11
2 10

I would like it to look like this:

1 10
1 10
1 11
2 10
2 11
2 10

3 Answers3

2

This will maintain the order of the lines within each grouping:

perl -ane '
    push @{$lines{$F[0]}}, $_;
   } {
    print join "", map {join "", @{$lines{$_}}} sort keys %lines;
' <<END
1 a
2 a
1 b
1 a
2 c
2 b
END
1 a
1 b
1 a
2 a
2 c
2 b
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

sort -k1,2 file.txt

produces

1 10
1 10
1 11
2 10
2 10
2 11
Chris Koknat
  • 3,305
  • 2
  • 29
  • 30
1

For this is better to use sort command

sort -k1n -s file.txt

Another solution using Gnu-awk 4, Controlling Scanning

gawk '
{d[$1][length(d[$1])+1]=$0}
END{
    PROCINFO["sorted_in"] = "@val_num_asc"; 
    for(key in d){
        for(i=1; i<=length(d[key]); ++i) {
            print d[key][i]
        }
    }
}' file.txt

you get,

1 10
1 10
1 11
2 10
2 11
2 10
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62