perl -we 'my $k = int(shift); my @a; my $l = 0; while (<>) { if ($l++ < $k) { push @a, $_ } else { if ((my $j = rand($l)) < $k) { $a[$j] = $_; } } } print @a;' 3 filename
##```
##
$ cat a
one
two
three
four
five
six
$ (for x in {1..33333}; do perl -we 'my $k = int(shift); my @a; my $l = 0; while (<>) { if ($l++ < $k) { push @a, $_ } else { if ((my $j = rand($l)) < $k) { $a[$j] = $_; } } } print @a;' 3 a | sort | tr \\n \ ; echo; done) | sort | uniq -c | sort -rn
1747 five four three
1736 five one six
1735 five three two
1725 four three two
1707 one six three
1695 five four two
1685 five six three
1684 five six two
1678 one three two
1666 five four six
1663 four six two
1663 four one six
1663 five four one
1645 four one two
1640 four six three
1637 five one three
1616 five one two
1592 six three two
1578 one six two
1578 four one three
$
```