开发者

change random line with shellscript

how can i easily (quick and dirty) change, say 10, random lines of a file with a simple shellscript?

i though about abusing ed and generating random commands and line ranges, but i'd开发者_Go百科 like to know if there was a better way


awk 'BEGIN{srand()}
{ lines[++c]=$0 }
END{
  while(d<10){
   RANDOM = int(1 + rand() * c)
   if( !( RANDOM in r)  ) {
     r[RANDOM]
     print "do something with " lines[RANDOM]
     ++d
   }
  }
}' file

or if you have the shuf command

shuf -n 10 $file | while read -r line
do
  sed -i "s/$line/replacement/" $file
done


Playing off @Dennis' version, this will always output 10. Doing random numbers in a separate array could create duplicates and, consequently, fewer than 10 modifications.

file=~/testfile
c=$(wc -l < "$file")
awk -v c=$c '
BEGIN {
        srand();
        count = 10;
    }

    {
        if (c*rand() < count) {
            --count;
            print "do something with " $0;
        } else
            print;
        --c;
    }
' "$file"


This seems to be quite a bit faster:

file=/your/input/file
c=$(wc -l < "$file")
awk -v c=$c 'BEGIN {
                    srand();
                    for (i=0;i<10;i++) lines[i] = int(1 + rand() * c);
                    asort(lines);
                    p = 1
             }
             {
                 if (NR == lines[p]) {
                     ++p
                     print "do something with " $0
                 }
                 else print 
             }' "$file"

I

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜