将 txt 文件转换为 csv

将 txt 文件转换为 csv

所以我的 file.txt 内容如下:

Symbol  Name    Sector  Market Cap, $K  Last    Links
 AAPL
Apple Inc
Computers and Technology
2,006,722,560
118.03
 AMGN
Amgen Inc
Medical
132,594,808
227.76
 AXP
American Express Company
Finance
91,986,280
114.24

我需要用它来实现:

Symbol,Name,Sector,Market Cap $K,Last
AAPL,Apple Inc,Computers and Technology,2006722560,118.03
AMGN,Amgen Inc,Medical,132594808,227.76
AXP,American Express Company,Finance,91986280,114.24

我尝试过这样的事情

sed 's/, / /g' table1.txt | tr "\t" " " | cut -d " " -f 1-6 | tr "\n" ","

带输出

Symbol Name Sector Market Cap $K Last, AAPL,Apple Inc,Computers and Technology,2,006,722,560,118.03, AMGN,Amgen Inc,Medical,132,594,808,227.76, AXP,American Express Company,Finance,91,986,280,114.24,

但这不是我所期望的,我不知道如何继续。

答案1

假设列标题字符串之间有制表符:

$ cat tst.awk
BEGIN { FS="\t"; OFS="," }
{ gsub(OFS,"") }
NR==1 {
    gsub(/[[:space:]]+[^[:space:]]+$/,"")
    numLines = NF
    $1 = $1
    print
    next
}
{
    lineNr = (NR-2) % numLines + 1
    gsub(/^[[:space:]]+|[[:space:]]+$/,"")
    rec = (lineNr == 1 ? "" : rec OFS) $0
    if ( lineNr == numLines ) {
        print rec
    }
}

$ awk -f tst.awk file
Symbol,Name,Sector,Market Cap $K,Last
AAPL,Apple Inc,Computers and Technology,2006722560,118.03
AMGN,Amgen Inc,Medical,132594808,227.76
AXP,American Express Company,Finance,91986280,114.24

答案2

这是一种方法:

$ awk '{ 
        if(NR==1){
            sub(/,/,"");    
            gsub(/   */,","); 
            print
        }
        else{ 
            if(NR%5==2){ 
                if(NR>2){print ""}
                printf "%s,",$0
            }
            else{
                printf "%s,",$0
            }
        }
    }
    END{print ""}' file
Symbol,Name,Sector,Market Cap $K,Last,Links
 AAPL,Apple Inc,Computers and Technology,2,006,722,560,118.03,
 AMGN,Amgen Inc,Medical,132,594,808,227.76,
 AXP,American Express Company,Finance,91,986,280,114.24,

您可以添加一些后处理来删除尾随,和前导空格:

$ awk '{ if(NR==1){sub(/,/,""); gsub(/   */,","); print}else{ if(NR%5==2 ){ if(NR>2){print ""}printf "%s,",$0}else{printf "%s,",$0}}}END{print ""}' file | sed 's/^  *//; s/,$//'
Symbol,Name,Sector,Market Cap $K,Last,Links
AAPL,Apple Inc,Computers and Technology,2,006,722,560,118.03
AMGN,Amgen Inc,Medical,132,594,808,227.76
AXP,American Express Company,Finance,91,986,280,114.24

答案3

使用 GNU sed

sed -z '
    s/,//g;
     # remove all commas
    s/\n\([^[[:blank:]]\)/,\1/g;
     # replace "\n" +a non-Tab/Space char with a comma and revert back char itself
    s/[[:blank:]][[:blank:]]\+/,/g;
     # replace repeated Tabs/Spaces with a comma 
' infile

无注释命令并删除前导空格:

sed -z '
    s/,//g;
    s/\n\([^[[:blank:]]\)/,\1/g;
    s/[[:blank:]][[:blank:]]\+/,/g; s/\n[[:blank:]]\+/\n/g;
' infile

相关内容