我怎样才能轻松(快速和肮脏)改变,比方说10,带有简单shellcript的文件的随机行?
我虽然关于滥用ed并生成随机命令和行范围,但我想知道是否有更好的方法
答案 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"