用shell脚本更改随机行

时间:2010-09-06 10:14:56

标签: shell random ed

我怎样才能轻松(快速和肮脏)改变,比方说10,带有简单shellcript的文件的随机行?

我虽然关于滥用ed并生成随机命令和行范围,但我想知道是否有更好的方法

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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"

答案 2 :(得分: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"