如何按比例将两个随机数之一添加到 csv 的每一行?

tbs*_*s35 1 csv random bash awk sed

我有一个包含 100 行和三列随机数的 csv:

100, 20, 30
746, 82, 928
387, 12, 287.3
12, 47, 2938
125, 198, 263
...
12, 2736, 14
Run Code Online (Sandbox Code Playgroud)

在 bash 中,我需要添加另一列,该列将是 0 或 1。但是,(这是困难的部分),我需要 20% 的行带有 0,80% 的行带有 1。结果:

100, 20, 30, 0
746, 82, 928, 1
387, 12, 287.3, 1
12, 47, 2938, 1
125, 198, 263, 0
...
12, 2736, 14, 1
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

sed '1~3s/$/0/' mycsv.csv
Run Code Online (Sandbox Code Playgroud)

但我认为我可以用“随机数”替换 1~3 但这不起作用。也许一个循环会?也许是 sed 或 awk?

Jam*_*own 5

使用 awk andrand()随机获得 0 和 1,有 20% 的概率获得 0:

$ awk 'BEGIN{OFS=", ";srand()}{print $0,(rand()>0.2)}' file
Run Code Online (Sandbox Code Playgroud)

输出:

100, 20, 30, 1
746, 82, 928, 1
387, 12, 287.3, 1
12, 47, 2938, 0
125, 198, 263, 1
..., 0
12, 2736, 14, 1
Run Code Online (Sandbox Code Playgroud)

解释:

$ awk '
BEGIN {
    OFS=", "                 # set output field separator
    srand()                  # time based seed for rand()
}
{
    print $0,(rand()>0.2)    # output 0/1 ~ 20/80
}' file
Run Code Online (Sandbox Code Playgroud)

由于srand()本身是时间(秒)为主,根据不同的需要,您可能希望引入外部种子它,例如,从击:

$ awk -v seed=$RANDOM 'BEGIN{srand(seed)}...'
Run Code Online (Sandbox Code Playgroud)

更新:首先计算文件中的行数,计算有多少是 20% 0 并随机选择 0 或 1 并保持计数的版本:

$ awk -v seed=$RANDOM '
BEGIN {
    srand(seed)                               # feed the seed to random
}
NR==1 {                                       # processing the first record
    while((getline line < FILENAME)>0)        # count the lines in the file
        nr++                                  # nr stores the count
    for(i=1;i<=nr;i++)                        # produce 
        a[(i>0.2*nr)]++                       # 20 % 0s, 80 % 1s
}
{
    p=a[0]/(a[0]+a[1])                        # probability to pick 0 or 1
    print $0 ". " (a[v=(rand()>p)]?v:v=(!v))  # print record and 0 or 1
    a[v]--                                    # remove 0 or 1
}' file
Run Code Online (Sandbox Code Playgroud)