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 に答える