Computing.Net > Forums > Unix > randomly select lines from a list

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

randomly select lines from a list

Reply to Message Icon

Name: badger
Date: April 15, 2008 at 12:24:34 Pacific
OS: Mac OSX
CPU/Ram: N/A
Product: mac
Comment:

Hi all,

I have a text file that has 142 lines each containing
several columns. I'm trying to write a script that will
randomly choose half of the lines, then write these to a
new text file. So, the result would be a file similar to the
original, but containing only 71 lines with none repeating.
Any advice/help would be greatly appreciated.

Nickles

b



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: April 15, 2008 at 13:17:42 Pacific
Reply:

Take a look at this thread:

http://www.computing.net/answers/un...

It describes using the shell's RANDOM number generator.

It doesn't talk about repeating lines. You'll have to save the lines already used.


0

Response Number 2
Name: ghostdog
Date: April 16, 2008 at 03:33:01 Pacific
Reply:


awk 'BEGIN{srand()}
!/^$/{ a[c++]=$0}
END {
for ( i=1;i<=c ;i++ ) {
num=int(rand() * c)
if ( a[num] ) {
print a[num]
delete a[num]
d++
}
if ( d == c/2 ) break
}
}' file



0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: randomly select lines from a list

Get the first line from a file www.computing.net/answers/unix/get-the-first-line-from-a-file/7981.html

Selecting specific lines from a fil www.computing.net/answers/unix/selecting-specific-lines-from-a-fil/8217.html

Script to delete lines from a file www.computing.net/answers/unix/script-to-delete-lines-from-a-file/7408.html