Bash: How to list n random number of files (not head or tail)

7

I have a large directory containing numerous files of similar kind. I have to send few random files for auditing. These files should not be from the top or bottom (eg. not in head or tail). This is sub process which I am struggling.

I want to get any number of files. It may be 10 or 2 or 3, but should not be in any order.

For example from this list of files:

10 1121231243 12 3124234ewdf 31243345 xaa 112 1121231243214 3 3124234ewdffd 3124334532 xab 1121 112123124321442334 3124 31243 3124334532324 xac 112123 1121ewszf 3124234 312433 file1

I would like to get a random subset like in this instance:

1121 112123124321442334 3124 1121ewszf

temp

Posted 2014-01-31T15:05:49.557

Reputation: 75

Why can't you use head or tail? Is this a homework assignment? – slhck – 2014-01-31T15:18:48.027

1I'm working in a company and I have encountered with a issue like this where It is a big directory, where some files in the middle, are to be sent for auditing. It's bigger issue and i got struck in this sub-process. – temp – 2014-01-31T15:24:45.570

2

It'd be better if you described the real issue instead of your attempted solution. Not only is this a contrived question, but you'd also end up with possibly useless answers. Can you [edit] your question and tell us more about the situation?

– slhck – 2014-01-31T15:27:06.707

Answers

8

Use random sort (-R or --random-sort) and then head or tail:

ls | sort -R | head -10

Michał Sacharewicz

Posted 2014-01-31T15:05:49.557

Reputation: 1 944

Thanks. In my case I needed the same 10 items always, but in random order ls | head -10 | sort -R – FindOutIslamNow – 2019-05-20T01:38:51.120

2

You can use sort -R to sort the list randomly, and then use the $RANDOM variable with head to get a random number of results:

ls | sort -R | head -n $(( $RANDOM % 10 + 1 ))

You will get 10 results or less (never zero)

GnP

Posted 2014-01-31T15:05:49.557

Reputation: 1 266