我是 Unix 新手,開始學習 shell 腳本。我正在使用帶有以下示例行的 CSV 檔案(這是一個大型 CSV 檔案,每個專案有 4 個條目):
Table 1
Item ID Time Available Location
0001 02/02/2021 08:00 Y NJ
0001 02/02/2021 09:00 N UT
0001 02/02/2021 10:00 Y AZ
0001 02/02/2021 11:00 Y CA
0002 02/02/2021 08:00 Y NJ
0002 02/02/2021 09:00 N UT
0002 02/02/2021 10:00 Y AZ
0002 02/02/2021 11:00 Y CA
我有另一個帶有一堆專案 ID 的 CSV,如下所示:
Table 2
Item ID Item_Name Item_Aux_ID Item_Aux_name
1001 IT_1 3323 IT_Aux_1
1002 IT_2 3325 IT_Aux_2
1003 IT_3 3328 IT_Aux_3
1010 IT_4 3333 IT_Aux_4
我想在第一個 CSV 檔案中創建新條目(第二個 CSV 檔案中的每個專案一個條目)。每個新條目應與 Table1 的第一行相同,并適當替換了專案 ID。預期的輸出將是:
Table 1
Item ID Time Available Location
0001 02/02/2021 08:00 Y NJ
0001 02/02/2021 09:00 N UT
0001 02/02/2021 10:00 Y AZ
0001 02/02/2021 11:00 Y CA
0002 02/02/2021 08:00 Y NJ
0002 02/02/2021 09:00 N UT
0002 02/02/2021 10:00 Y AZ
0002 02/02/2021 11:00 Y CA
1001 02/02/2021 08:00 Y NJ
1002 02/02/2021 08:00 Y NJ
1003 02/02/2021 08:00 Y NJ
1010 02/02/2021 08:00 Y NJ
我如何撰寫腳本來在 Unix 中實作上述功能?提前致謝。
uj5u.com熱心網友回復:
一個awk想法:
awk '
NR==3 { # 1st file: skip 1st two lines (the header rows) then ...
copyline=$0 # make a copy of the 3rd line and ...
nextfile # skip to the next file
}
FNR>2 { # 2nd file: skip 1st two lines (the header rows) and ...
# replace the 1st field of variable "copyline" with 1st field of current input line and ...
# print the modified "copyline" to stdout
print gensub(/^[^[:space:]]*/,$1,1,copyline)
}
' file1.csv file2.csv
已洗掉評論:
awk '
NR==3 { copyline=$0; nextfile }
FNR>2 { print gensub(/^[^[:space:]]*/,$1,1,copyline) }
' file1.csv file2.csv
進一步折疊成單行:
awk 'NR==3{copyline=$0;nextfile}FNR>2{print gensub(/^[^[:space:]]*/,$1,1,copyline)}' file1.csv file2.csv
這會產生:
1001 02/02/2021 08:00 Y NJ
1002 02/02/2021 08:00 Y NJ
1003 02/02/2021 08:00 Y NJ
1010 02/02/2021 08:00 Y NJ
一旦 OP 對輸出感到滿意,并假設希望將輸出附加到第一個檔案,那么......
# change this:
' file1.csv file2.csv
# to this:
' file1.csv file2.csv >> file1.csv
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/391306.html
