2017-08-16 45 views
0

我有一個包含目錄列表的電子表格,並且需要將相關的可變數量的「帳戶」分配給每個目錄(可以輕鬆轉換爲csv)即:根據csv使用linux將文件拆分爲可變數量和目錄

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拆分爲分隔符e accounts.csv文件的每個唯一目錄與所需的帳戶數量。

master_file經常使用新帳戶進行更新,並且需要重新分配給所有目錄。 (生成的accounts.csv文件與master_account_list具有相同的格式。)

在Linux中完成的最佳方式是什麼?

編輯:當腳本完成時,如果master_account_list.csv中剩餘的未分配帳戶成爲新的master_account_list.csv,那將是理想的。

+0

我已經投票結束這個問題,因爲它似乎是一個工具或解決方案的建議的請求,而不是請求幫助您自己的代碼。這使您的問題脫離了StackOverflow。如果該評估不正確,並且確實需要編寫自己的代碼,請[將您的工作添加到您的問題中](https://stackoverflow.com/posts/45724561/edit),然後我會愉快地收回我的近距離投票。 – ghoti

回答

0

假定你已經轉換帳戶spreasheet以逗號分隔的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是不允許的計入當前的實施。

+0

謝謝 - 這個作品很棒! ... ..我對Linux和awk命令的新手道歉。非常感謝這些初學者提示:-) – Kelly

+0

很高興看到它適合你 – hek2mgl

+0

...後續:我注意到這附加了現有的文件,我想替換。我還需要在新文件中使用單行標題。目前,我正在使用批處理'cp'來替換每個文件,以將包含標題的新空白文件複製到每個目錄。然後我運行這個腳本。我可以使用awk來完成相同的操作嗎? – Kelly