簡體   English   中英

在多個輸入文件上使用awk

[英]Using awk on multiple input files

我一直在處理一個bash腳本,並且在該腳本中的某個時刻,我一直在嘗試弄清楚如何使用awk一次處理兩個CSV文件,該文件將用於生成多個輸出文件。 不久,就有一個主文件,該文件將要分發的內容保留到其他一些輸出文件中,這些文件的名稱和需要保留的記錄數將從另一個文件派生。 n記錄將進入第一個輸出文件,隨后n+1n+k進入第二個文件,依此類推。

為了更加清楚,這是一個主記錄文件的外觀示例:

x11,x21
x12,x22
x13,x23
x14,x24
x15,x25
x16,x26
x17,x27
x18,x28
x19,x29

以及其他文件的外觀:

out_file_name_1,2
out_file_name_2,3
out_file_name_3,4

然后,第一個名為out_file_name_1輸出文件應如下所示:

x11,x21
x12,x22

然后,第二個名為out_file_name_2輸出文件應如下所示:

x13,x23
x14,x24
x15,x25

最后一個應該看起來像:

x16,x26
x17,x27
x18,x28
x19,x29

希望它已經足夠清楚了。

自您提出以來,這是awk中的解決方案,但顯然,三元組的答案是更好的方法。

$ cat oak.awk
BEGIN { FS = ","; fidx = 1 }

# Processing files.txt, init parallel arrays with filename and number of records
# to print to each one.
NR == FNR {
    file[NR] = $1
    records[NR] = $2
    next
}

# Processing main.txt. Print record to current file. Decrement number of records to print,
# advancing to the next file when number of records to print reaches 0
fidx in file && records[fidx] > 0 {
    print > file[fidx]
    if (! --records[fidx]) ++fidx
    next
}

# If we get here, either we ran out of files before reading all the records
# or a file was specified to contain zero records    
{ print "Error: Insufficient number of files or file with non-positive number of records"
  exit 1 }


$ cat files.txt
out_file_name_1,2
out_file_name_2,3
out_file_name_3,4

$ cat main.txt
x11,x21
x12,x22
x13,x23
x14,x24
x15,x25
x16,x26
x17,x27
x18,x28
x19,x29

$ awk -f oak.awk files.txt main.txt

$ cat out_file_name_1
x11,x21
x12,x22

$ cat out_file_name_2
x13,x23
x14,x24
x15,x25

$ cat out_file_name_3
x16,x26
x17,x27
x18,x28
x19,x29

我不會為此使用Awk。

while IFS=, read -u 3 filename lines; do
    head -n "$lines" >"$filename"
done 3<other.csv <main.csv

我相信,從特定文件描述符讀取的read -u並不是完全可移植的,但是您的問題被標記為所以我假設這里不是問題。

演示: http : //ideone.com/6FisHT

如果您在第一個文件之后得到空文件,則可以嘗試使用其他read語句替換內部循環。

while IFS=, read -u 3 filename lines; do
    for i in $(seq 1 "$lines"); do
        read -r line
        echo "$line"
    done >"$filename"
done 3<other.csv <main.csv

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM