shell 腳本的新手..
我有一個巨大的 csv 檔案,具有不同長度的 f11,例如
"000000aaad000000bhb200000uwwed..."
"000000aba200000bbrb2000000wwqr00000caba2000000bhbd000000qwew..."
. .
將字串拆分為 10 大小后,我需要 6-9 個字符。然后我必須使用分隔符 '|' 將它們重新加入 喜歡
0aaa|0bhb|uwwe...
0aba|bbrb|0wwq|caba|0bhb|0qwe...
并將處理后的 f11 與其他欄位連接
這是處理 10k 條記錄所需的時間 ->
真正的 4m43.506s
用戶 0m12.366s
系統 0m12.131s
20K 記錄 ->
真實 5m20.244s
用戶 2m21.591s
sys 3m20.042s
8 萬條記錄(大約 370 萬條 f11 拆分并與“|”合并)->
真實 21m18.854s
用戶 9m41.944s
系統 13m29.019s
我的預期時間是 30 分鐘處理 65 萬條記錄(大約 56 百萬 f11 拆分和合并)。有什么辦法優化嗎?
while read -r line1; do
f10=$( echo $line1 | cut -d',' -f1,2,3,4,5,7,9,10)
echo $f10 >> $path/other_fields
f11=$( echo $line1 | cut -d',' -f11 )
f11_trim=$(echo "$f11" | tr -d '"')
echo $f11_trim | fold -w10 > $path/f11_extract
cat $path/f11_extract | awk '{print $1}' | cut -c6-9 >> $path/str_list_trim
arr=($(cat $path/str_list_trim))
printf "%s|" ${arr[@]} >> $path/str_list_serialized
printf '\n' >> $path/str_list_serialized
arr=()
rm $path/f11_extract
rm $path/str_list_trim
done < $input
sed -i 's/.$//' $path/str_list_serialized
sed -i 's/\(.*\)/"\1"/g' $path/str_list_serialized
paste -d "," $path/other_fields $path/str_list_serialized > $path/final_out
uj5u.com熱心網友回復:
由于以下原因,您的代碼不省時:
- 在回圈中呼叫包括 awk 在內的多個命令。
- 生成許多??中間時間檔案。
你可以只用 awk 來完成這項作業:
awk -F, -v OFS="," ' # assign input/output field separator to a comma
{
len = length($11) # length of the 11th field
s = ""; d = "" # clear output string and the delimiter
for (i = 1; i <= len / 10; i ) { # iterate over the 11th field
s = s d substr($11, (i - 1) * 10 6, 4) # concatenate 6-9th substring of 10 characters long chunks
d = "|" # set the delimiter to a pipe character
}
$11 = "\"" s "\"" # assign the 11th field to the generated string
} 1' "$input" # the final "1" tells awk to print all fields
輸入示例:
1,2,3,4,5,6,7,8,9,10,000000aaad000000bhb200000uwwed
1,2,3,4,5,6,7,8,9,10,000000aba200000bbrb2000000wwqr00000caba2000000bhbd000000qwew
輸出:
1,2,3,4,5,6,7,8,9,10,"0aaa|0bhb|uwwe"
1,2,3,4,5,6,7,8,9,10,"0aba|bbrb|0wwq|caba|0bhb|0qwe"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/336810.html
下一篇:Pangram檢測
