1

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 like to know if there was a better way

4

3 回答 3

2
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

或者如果你有shuf命令

shuf -n 10 $file | while read -r line
do
  sed -i "s/$line/replacement/" $file
done
于 2010-09-06T10:31:00.580 回答
2

这似乎要快一些:

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"

于 2010-09-06T16:08:17.430 回答
2

播放@Dennis 的版​​本,这将始终输出 10。在单独的数组中执行随机数可能会创建重复,因此修改次数少于 10。

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"
于 2010-09-07T02:38:17.140 回答