choose random text between constant string.. using awk?

Hallo
I have maybe a little bit advanced request....
I need to choose one random part betwen %....

so i have this..

%
text1 text1 text1
text1 text1 text1
text1 text1 text1
%
text2 text2
text2 text2 text2
%
text3 text3 text3
tetx3
%

this choose text between %

awk ' /%/ {flag=1;next} /%/{flag=0} flag { print }' file

so i get

text1 text1 text1
text1 text1 text1
text1 text1 text1
text2 text2
text2 text2 text2
text3 text3 text3
tetx3

I NEED JUST ONE PART

text1 text1 text1
 text1 text1 text1
 text1 text1 text1

or

text2 text2
 text2 text2 text2

or

text3 text3 text3
 tetx3

Any help would be appreciate....

Your solution is equivalent to:

awk '/%/{next}{print}' infile

This should print only the first segment:

awk '/%/{p++;next}p==1{print}' infile

This the second:

awk '/%/{p++;next}p==2{print}' infile

etcetera

Thank you very much Scrutinizer.... this helped me a lot...

awk '/%/{p++;next}p==1{print}' infile

try the next code uses rand function

awk 'BEGIN{ RS="%"  ;srand() } { line[NR] = $0 } END{ print line[randint(NR)] } function randint(n) {return int(n * rand()) + 1}' infile 

Or

awk 'BEGIN{ RS="%\n"  ;srand() } { line[NR] = $0 } END{ print line[int((NR* rand()) + 1)]}'  infile 

Very nice ironmask2004 it is great too ....

I have just finished it with the previous solution

vtip=$RANDOM
let "vtip=1+(vtip%2125)"
awk -v cislo=$vtip '/%/{p++;next}p==cislo' vtipy.txt

but you need to know how muche recoreds you have insaide the fill to generate a random number betwwen 1 and NUM Of Rec !!!

yes good question i have used

grep -c "^[%]" vtipy.txt

and the number was 2126

vtip=$RANDOM
let "vtip=1+(vtip%2125)"   #thats why here is 2125 it is modulo
awk -v cislo=$vtip '/%/{p++;next}p==cislo' vtipy.txt

:b:


  1. % ↩︎

Hi.

If one is willing to devote the time and effort, the reservoir sampling method allows one to extract a random sample in a single pass through a file. A brief explanation along with a python and perl code can be found at Program-o-Babble: Reservoir Sampling Algorithm in Python and Perl among many other places.

Best wishes ... cheers, drl