Karthik
Karthik

Reputation: 2581

Random strings from a list of strings

I have a list of strings, I want to pick up strings from that list randomly. Could you anyone help me out with perl or awk.

String List:

John
Peter
Adam
Mike
Charlie
Sanders
William
...

Output:

Peter
Mike
Sanders
...

Upvotes: 1

Views: 720

Answers (4)

Leonid Sopov
Leonid Sopov

Reputation: 9

print splice(@a,rand(@a),1),"\n" while @a;

where @a our list g.e. my @a = qw/ John Peter Adam Mike Charlie Sanders William /;

Upvotes: 0

meme
meme

Reputation: 12197

Create a file with your words, a new word on each line. Then run this script to pick a selected number (example below is showing 5) of the words out of the list.

#!/usr/bin/perl -l

sub random_words {
$random_items = $_[0];

open(DB, 'random-words.db');
@words = <DB>;
close DB;

    for ($i=0; $i < $random_items; $i++) {
        $random_index = int(rand(@words));
        $random_word = $words[$random_index];
        $random_word =~ s/\R//g;
        print $random_word;
    }
}

random_words(5);

Upvotes: 1

Borodin
Borodin

Reputation: 126722

The List::Util module provides a shuffle operator. It is also a core module and so shouldn't need installing

use strict;
use warnings;

use List::Util 'shuffle';

open my $fh, '<', 'string_list.txt' or die $!;
my @names = <$fh>;

print for (shuffle @names)[0..499];

Upvotes: 2

daxim
daxim

Reputation: 39158

I assume you have those names in a file.

use File::Slurp qw(read_file);
use List::Util qw(shuffle);
print for (shuffle read_file 'the_input_file_name' )[0..499];

Upvotes: 4

Related Questions