Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I wish to take 10 random lines of file, which is 100 lines long. First, I randomly generate 10 integers between 1 and 100 (inclusive) with

ind=$(shuf -i 1-100 -n 10 | sort -n)

Then, I wish to use sed to extract out those lines (indicated by ind). So I need to re-print the array ind to generate

<ind(1)>p;<ind(2)>p;...;<ind(10)>p

as in

sed -n '<ind(1)>p;<ind(2)>p;...;<ind(10)>p' ~/orig.txt > ~/short.txt

How may I do this?

share|improve this question

2 Answers 2

In your example, ind is a string, not an array. You must use:

ind=($(shuf -i 1-100 -n 10 | sort -n))

to make ind to be array (in shell support array like bash, zsh, ksh).

Simply, you can try:

$ printf '%sp\n' $(shuf -i 1-100 -n 10 | sort -n) > /tmp/short.sed
$ sed -n -f /tmp/short.sed < orig.txt > short.txt
share|improve this answer

An awk based solution (without need of sorting):

awk 'NR==FNR{a[$1];next} NR in a' <(shuf -i 1-100 -n 10) ~/orig.txt > ~/short.txt

And a pure GNU awk variant (without need of other external processes):

awk '
  BEGIN { srand(); do a[int(100*rand()+1)]; while (length(a)<10) }
  NR in a
' ~/orig.txt > ~/short.txt
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.