我有一長串未格式化的資料說 data.txt ,其中每組都以標題開頭并以空行結尾,例如:
TypeA/Price:20$
alexmob
moblexto
unkntom
TypeB/Price:25$
moblexto2
unkntom0
alexmob3
poptop9
tyloret
TypeC/Price:30$
rtyuoper0
kunlohpe6
mobryhox
現在,我想將每個集合的標題與它的內容并排添加,并用逗號分隔。喜歡:
alexmob,TypeA/Price:20$
moblexto,TypeA/Price:20$
unkntom,TypeA/Price:20$
moblexto2,TypeB/Price:25$
unkntom0,TypeB/Price:25$
alexmob3,TypeB/Price:25$
poptop9,TypeB/Price:25$
tyloret,TypeB/Price:25$
rtyuoper0,TypeC/Price:30$
kunlohpe6,TypeC/Price:30$
mobryhox,TypeC/Price:30$
這樣每當我使用一個關鍵字進行 grep 時,相關內容以及標題都會聚集在一起。喜歡:
$grep mob data.txt
alexmob,TypeA/Price:20$
moblexto,TypeA/Price:20$
moblexto2,TypeB/Price:25$
alexmob3,TypeB/Price:25$
mobryhox,TypeC/Price:30$
我是 bash 腳本和 python 的新手,最近開始學習這些,所以非常感謝任何簡單的 bash scipting(使用 sed/awk)或 python 腳本。
uj5u.com熱心網友回復:
使用sed
$ sed '/Type/{h;d;};/[a-z]/{G;s/\n/,/}' input_file
alexmob,TypeA/Price:20$
moblexto,TypeA/Price:20$
unkntom,TypeA/Price:20$
moblexto2,TypeB/Price:25$
unkntom0,TypeB/Price:25$
alexmob3,TypeB/Price:25$
poptop9,TypeB/Price:25$
tyloret,TypeB/Price:25$
rtyuoper0,TypeC/Price:30$
kunlohpe6,TypeC/Price:30$
mobryhox,TypeC/Price:30$
匹配包含 的行Type,將其保存在記憶體中并洗掉它。
匹配帶有字母字符的行,附加G保留空間的內容。最后,用逗號換行。
uj5u.com熱心網友回復:
我會AWK按照以下方式使用 GNU 來完成這項任務,讓file.txt內容成為
TypeA/Price:20$
alexmob
moblexto
unkntom
TypeB/Price:25$
moblexto2
unkntom0
alexmob3
poptop9
tyloret
TypeC/Price:30$
rtyuoper0
kunlohpe6
mobryhox
然后
awk '/^Type/{header=$0;next}{print /./?$0 ";" header:$0}' file.txt
輸出
alexmob;TypeA/Price:20$
moblexto;TypeA/Price:20$
unkntom;TypeA/Price:20$
moblexto2;TypeB/Price:25$
unkntom0;TypeB/Price:25$
alexmob3;TypeB/Price:25$
poptop9;TypeB/Price:25$
tyloret;TypeB/Price:25$
rtyuoper0;TypeC/Price:30$
kunlohpe6;TypeC/Price:30$
mobryhox;TypeC/Price:30$
說明:如果行以 ( ^)開頭,則將值Type設定header為該行 ( $0) 并轉到next行。對于每一行print,如果它確實包含至少一個字符 ( /./),則行 ( $0) 與;and連接header,否則按原樣列印行 ( $0)。
(在 GNU Awk 5.0.1 中測驗)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/455931.html
