Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I can try. -ne modifiers are just to say to execute the script on every line of input. The body that will be executed in pseudo code is

    while get_input:
      if rand() < 1 / current_line_number:  # $. contains the line number of input
        l := current_line_content  # $_ always contains "what you want", in this case the current line

    # when using -n flat you can use BEGIN {} and END {} blocks
    # to execute code before and after the loop
    print(l)
Now, as to why the random selection works, this is a simplified version of Reservoir Sampling[1]

[1]: https://en.wikipedia.org/wiki/Reservoir_sampling



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: