[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Needing a random number generator for scripting



Hi,

Jeremy Whetzel <thinker5555@yahoo.com> writes:

> I'm in the process of writing up a script that I need to be able to
> "randomly" switch around the lines in a text file.  (ala a random mp3
> playlist) Would anyone have any suggestions?  I was originally thinking
> of using a random number generator for it, but if there's a tool that
> would work better...?

If you have 'bash', you can use:

  # scale should be larger than number of lines
  scale=1000

  # number of lines in file

  ## if the file is fixed, you can hardcode this value
  ## otherwise, if the format has a count on the first line (like
  ##    fonts.dir), you can use
  ##  lines=`head -1 file`
  ## and change the '1' in the dc command below to '2'.

  lines=`wc -l file`

  # pick a random line
  line=`echo "$RANDOM $scale * 32768 / $lines * $scale / 1 + p" | dc`

  # print only that line
  sed -n "${line}p" file

- Hari
-- 
Raja R Harinath ------------------------------ harinath@cs.umn.edu
"When all else fails, read the instructions."      -- Cahn's Axiom
"Our policy is, when in doubt, do the right thing."   -- Roy L Ash



Reply to: