0

How do I pick a random row of text from a file?

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • 6
    Should "any row" be interpreted as "a random row" specifically, or are you just looking for the top or bottom row? This question is _trivial_ to solve. I'm just a bit confused by the haphazard "any row". – Kusalananda Jan 30 '19 at 06:40
  • Just any random row – Sanapa Karthik Jan 30 '19 at 16:21
  • How random? `head -n 1 file` will give you the first row, `tail -n 1 file` will give you the last one. – Kusalananda Jan 30 '19 at 16:26
  • Not the head and tail rows it can be any row ,suppose I have 100 rows ,the output should be like only one row out of that 100 rows(that one row can be from 1-100) – Sanapa Karthik Jan 30 '19 at 17:06
  • The question currently asks for "any row", but you _specifically want a random row_. This is different from "any row". – Kusalananda Jan 30 '19 at 17:16
  • The question is now a duplicate of [How to randomly sample a subset of a file](//unix.stackexchange.com/q/108581) (with 1000 changed to 1). Or possibly of [Randomly draw a certain number of lines from a data file](//unix.stackexchange.com/q/29709) (or both). – Kusalananda Jan 30 '19 at 17:20
  • See also https://unix.stackexchange.com/q/326535/117549 – Jeff Schaller Jan 30 '19 at 18:13
  • See also: https://unix.stackexchange.com/questions/277242/print-specific-line-from-multiple-files – Jeff Schaller Jan 30 '19 at 18:28
  • `n=$(wc -l <"$path"); head -$[(RANDOM<<15+RANDOM)%n] "$path"|tail -1` The distribution won't be perfectly level and it will see only the first billion lines of large textfiles. The location of the file should be in the `path` environment variable. – peterh Jan 30 '19 at 18:34

0 Answers0