簡體   English   中英

Bash-從TXT生成CSV文件

[英]Bash - Built a CSV File from TXT

我是使用bash和grep的新手...我正嘗試從包含以下行的TXT文件中輸出CSV文件:

輸入:

1. Fisrt - Name: Joanna Last - Name: Yang
Place of birth: Paris Date of birth: 01/01/1972 Sex: F
Number: 0009876541234567
2. Fisrt - Name: Bob Last - Name: Lee
Place of birth: London Date of birth: 05/08/1969 Sex: M
Number: 0005671890765223

輸出:

"Joanna","Yang","Paris","01/01/1972","F","0009876541234567"
"Bob","Lee","London","05/08/1969","M","0005671890765223"

任何建議,將不勝感激!!!!

僅使用一個帶有grep的正則表達式並不容易。
您可以嘗試使用多個正則表達式並合並結果。

例如:
要獲取名字,您可以使用以下正則表達式: "Fisrt - Name: ([a-zA-Z]+)"
將其保存到變量中。

接下來要獲取出生日期,您可以使用"birth: ([0-9]+\\/[0-9]+\\/+[0-9]+)"
將其保存到變量中。

對每個部分執行此操作,並用逗號將結果連接起來。

顯然這不是最好的方法,但這是一個開始。 為了幫助使用正則表達式,您可以使用https://regex101.com/

也許嘗試使用sed命令行

如果您的文件格式很好並且格式很好,則不需要正則表達式。
我們一次可以讀取三行,並在空格處分割它們-我們僅對指定的字段感興趣。 如果您可以“斷言”文件中的任何字段都不包含空格(我認為其中沒有有效的人名...,對嗎?),您可以這樣做:

while
    IFS=' ' read -r _ _ _ _ name _ _ _ last &&
    IFS=' ' read -r _ _ _ birthplace _ _ _ birthdate _ sex &&
    IFS=' ' read -r _ number
do
    printf '"%s","%s","%s","%s","%s","%s"\n' \
        "$name" "$last" "$birthplace" "$birthdate" "$sex" "$number"
done <input

在線版本可在onlinedbg獲得

一行:

~ $ cat yourfile.txt 
1. Fisrt - Name: Joanna Last - Name: Yang
Place of birth: Paris Date of birth: 01/01/1972 Sex: F
Number: 0009876541234567
2. Fisrt - Name: Bob Last - Name: Lee
Place of birth: London Date of birth: 05/08/1969 Sex: M
Number: 0005671890765223
~ $ sed -r "s/^.*Fisrt - Name: (.*) Last - Name: (.*)$/\1,\2;/g" yourfile.txt | sed -r "s/^Place of birth: (.*) Date of birth: (.*) Sex: (.*)$/\1,\2,\3;/g" | sed -r "s/^Number: (.*)$/\1/g" | sed -n 'H;${x;s/;\n/,/g;s/^,//;p;}' | tail -n +2 > yourfile.csv
~ $ cat yourfile.csv 
Joanna,Yang,Paris,01/01/1972,F,0009876541234567
Bob,Lee,London,05/08/1969,M,0005671890765223
~ $ 

希望能幫助到你。

暫無
暫無

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

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