簡體   English   中英

我無法通過awk處理數據

[英]I'm not able to process data through awk

我正在嘗試使用awk處理數據,但無法獲得正確的結果。如果在某處做錯了,請告知數據:-test.txt

"A","B","ls",,"This,is,the,test",T,
"k",O,"mv",,"This,is,the,2nd test","L",
"C",J,"cd",,"This,is,the,3rd test",,

awk  'BEGIN { FS=","; OFS="|" }  { nf=0; delete f; while ( match($0,/([^,]+)|(\"[^\"]+\")/) ) { f[++nf] = substr($0,RSTART,RLENGTH); $0 = substr($0,RSTART+RLENGTH); };  print f[2],f[3],f[4],f[5] }' test.txt 

烏普特

"B"|"ls"|"This,is,the,test"|T
O|"mv"|"This,is,the,2nd test"|"L"
J|"cd"|"This,is,the,3rd test"|

但是輸出應該是這樣的

"B"|"ls"||"This,is,the,test"|T
O|"mv"||"This,is,the,2nd test"|"L"
J|"cd"||"This,is,the,3rd test"|
awk -F\" '{q="\""; print q$4q"|"q$6q"||"q$8q}'
awk -vFPAT='"[^"]*"' '{$0=$2"|"$3"||"$4}1' FILE

使用拍

使用您的新輸入和任何awk:

$ cat tst.awk
BEGIN { FS=","; OFS="|" }
{
    # 1) Replace all FSs inside quotes with the value of RS
    #    since we know that RS cannot be present in any record:
    head = ""
    tail = $0
    while( match(tail,/"[^"]+"/) ) {
        trgt = substr(tail,RSTART,RLENGTH)
        gsub(FS,RS,trgt)
        head = head substr(tail,1,RSTART-1) trgt
        tail = substr(tail,RSTART+RLENGTH)
    }
    $0 = head tail

    # 2) re-compile the record to replace FSs with OFSs:
    $1 = $1

    # 3) restore the RSs within quoted fields to FSs:
    gsub(RS,FS)

    # 4) remove the first and last fields:
    gsub("^[^" OFS "]*[" OFS "]|[" OFS "][^" OFS "]*$","")

    print
}

$ awk -f tst.awk file
"B"|"ls"||"This,is,the,test"|T
O|"mv"||"This,is,the,2nd test"|"L"
J|"cd"||"This,is,the,3rd test"|

暫無
暫無

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

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