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

おすすめ記事