linux - 使用linux基于csv将文件拆分为可变数量和目录

标签 linux bash csv split

我有一个包含目录列表的电子表格,并且需要为每个目录分配一个相关的可变数量的“帐户”(可以很容易地转换为 csv)即:

directory                  # of accounts needed
/usr/src/Mon-Carlton/      110
/usr/src/Mon-CoalMtn/      50                                                                                    
/usr/src/Mon-Cumming/      90
etc... 

我还有一个“master_account_list.csv”文件,其中包含可分配到每个区域的所有可能帐户的完整列表,即:

account_1,password,type
account_2,password,type
account_3,password,type
etc...

我希望能够编写将 master_account_list.csv 拆分为单独的 accounts.csv 文件的脚本,用于每个具有列出的所需帐户数量的唯一目录。

master_file 经常用新帐户更新,需要重新分发到所有目录。 (生成的 accounts.csv 文件与 master_account_list 具有相同的格式。)

那么在 Linux 中最好的实现方式是什么?

编辑:当脚本完成时,如果 master_account_list.csv 中剩余的未分配账户成为新的 master_account_list.csv 将是理想的。

最佳答案

假设您已将帐户电子表格转换为逗号 (!) 分隔的 csv 文件,没有标题 (!),您可以使用以下 awk 程序:

split_accounts.awk:

# True as long as we are reading the first file which
# is the converted spreadsheet
NR==FNR {
    # Store the directories and counts in arrays
    dir[NR]=$1
    cnt[NR]=$2
    next
}

# This block runs for every line of master_account_list.csv
{
    # Get the directory and count from the arrays we've
    # created above. 'i' will get initialized automatically
    # with 0 on it's first usage
    d=dir[i+1]
    c=cnt[i+1]

    # append the current line to the output file
    f=d"account_list.csv"
    print >> f

    # 'n' holds the number of accounts placed into the current
    # directory. Check if it has the reached the desired count
    if(++n==c) {
        # Step to the next folder / count
        i++
        # Reset the number of accounts placed
        n=0
        # Close the previous output file
        close(f)
    }
}

这样调用它:

awk -F, -f split_accounts.awk accounts.csv master_account_list.csv

注意:0 在当前实现中不允许用于计数。

关于linux - 使用linux基于csv将文件拆分为可变数量和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724561/

相关文章:

java - 在多个输入文件上运行终端程序

linux - 打破 Bash 中的嵌套函数循环

r - 仅从 R 中的 .csv 文件导入每第 N 行

java - Youtrack 安装,未找到 Java

linux - 在 shell/linux 中 grep 查找文本文件第一列中的特定字符串

Linux 每程序防火墙类似于 windows 和 mac 对应物

android - 如何直接从网络上的 CSV 导入

c++ - 列出在 Linux 上使用 C/C++ 执行的程序中的共享库

linux - 如何在 bash 中识别文件夹然后决定是否移动它

shell - 打印 CSV 的前 N ​​行,其中引用的字段可以包含换行符