Reputation: 55
I need to, using a UNIX command line script, get 11 random lines from a file that are grouped together. For instance
Random source file:
1
2
3
4
5
6
7
8
9
10
11
############
12
13
14
15
16
17
18
19
20
21
22
Running ./myscript
should give me:
1
2
3
4
5
6
7
8
9
10
11
or
12
13
14
15
16
17
18
19
20
21
22
Upvotes: 2
Views: 152
Reputation: 455460
You can try:
n=$((`wc -l "${file}" | cut -d' ' -f1` / 11))
m=$(($RANDOM % $n))
tail -n +$(($m * 11)) "${file}" | head -n 11
Upvotes: 0
Reputation: 394034
tail -n +$(($RANDOM %
($(wc -l "$filename" | cut -d' ' -f1) - 11))) "$filename" |
head -n 11
With
export filename=/etc/dictionaries-common/words
set -o xtrace
first time
~$ tail -n +$(($RANDOM % ($(wc -l "$filename" | cut -d' ' -f1) - 11))) "$filename" | head -n 11
+ head -n 11
++ wc -l /etc/dictionaries-common/words
++ cut '-d ' -f1
+ tail -n +11614 /etc/dictionaries-common/words
Moriarty's
Morin
Morin's
Morison
Morison's
Morita
Morita's
Morley
Morley's
Mormon
Mormon's
second time
~$ tail -n +$(($RANDOM % ($(wc -l "$filename" | cut -d' ' -f1) - 11))) "$filename" | head -n 11
+ head -n 11
++ wc -l /etc/dictionaries-common/words
++ cut '-d ' -f1
+ tail -n +1661 /etc/dictionaries-common/words
Beatrice
Beatrice's
Beatrix
Beatrix's
Beatriz
Beatriz's
Beau
Beau's
Beaufort
Beaufort's
Beaujolais
Upvotes: 2