1

这是我的代码:

nb_lignes=`wc -l $1 | cut -d " " -f1`
for i in $(seq $nb_lignes)
do
m=`head $1 -n $i | tail -1`
//command
done

请问如何更改它以随机获取文件中 20% 的行以在每行上应用“命令”?20% 或 40% 或 60 %(这是一个参数)

谢谢你。

4

4 回答 4

1

This will randomly get 20% of the lines in the file:

awk -v p=20 'BEGIN {srand()} rand() <= p/100' filename

So something like this for the whole solution (assuming bash):

#!/bin/bash
filename="$1"
pct="${2:-20}"     # specify percentage
while read line; do
  : # some command with "$line"
done < <(awk -v p="$pct" 'BEGIN {srand()} rand() <= p/100'  "$filename")

If you're using a shell without command substitution (the <(...) bit), you can do this - but the body of the loop won't be able to have any side effects in the outer script (e.g. any variables it sets won't be set anymore once the loop completes):

#!/bin/sh
filename="$1"
pct="${2:-20}"     # specify percentage
awk -v p="$pct" 'BEGIN {srand()} rand() <= p/100'  "$filename" | 
 while read line; do
   : # some command with "$line"
 done
于 2012-09-28T10:04:53.877 回答
0

你可以用 awk 做到这一点。见下文:

awk -v b=20 '{a[NR]=$0}END{val=((b/100)*NR)+1;for(i=1;i<val;i++)print a[i]}' all.log

上面的命令打印从文件开头开始的所有行的 20%。

您只需在命令行上更改 b 的值即可获得所需的 % 行数。测试如下:

> cat temp
1
2
3
4
5
6
7
8
9
10
> awk -v b=10 '{a[NR]=$0}END{val=((b/100)*NR)+1;for(i=1;i<val;i++)print a[i]}' temp
1
> awk -v b=20 '{a[NR]=$0}END{val=((b/100)*NR)+1;for(i=1;i<val;i++)print a[i]}' temp
1
2
>
于 2012-09-28T10:01:20.657 回答
0

shuf 将以随机顺序生成文件;如果你知道你想要多少行,你可以给 -n 参数。无需一次获得一个。所以:

shuf -n $(( $(wc -l < $FILE) * $PCT / 100 )) "$file" |
while read line; do 
  # do something with $line
done

shuf 是 GNU/Linux 发行版 afaik 的标准配置。

于 2012-09-29T03:51:13.730 回答
0

尝试这个:

file=$1
nb_lignes=$(wc -l $file | cut -d " " -f1)
num_lines_to_get=$((20*${nb_lignes}/100)) 
for (( i=0; i < $num_lines_to_get; i++))
do
  line=$(head -$((${RANDOM} % $nb_lignes)) $file | tail -1)
  echo "$line"
done

请注意,${RANDOM}仅生成小于 32768 的数字,因此此方法不适用于大文件。

如果你已经shuf安装了,你可以使用下面的来获取随机行,而不是使用$RANDOM.

line=$(shuf -n 1 $file)
于 2012-09-28T09:59:13.177 回答