2013-11-26 3 views
1

원본 파일에 하나의 문제가 있습니다. 파일에 다음 데이터가 있다고 가정하십시오.소스 파일 구분 기호 문제

"dfjsdlfkj,fsdkfj,werkj",234234,234234,,"dfsd,etwetr" 

여기에서 구분 기호는 쉼표이지만 일부 필드는 쉼표를 데이터의 일부로 포함합니다. 이러한 필드는 큰 따옴표로 묶습니다. 파일에서 몇 개의 열을 추출하고 싶습니다. 내가 cut -d "," -f 1,3를 사용하는 경우

그때는 무엇입니까 다음과 같은 시도 할 수

"dfjsdlfkj,werkj" 
+0

중복 가능성 http://stackoverflow.com/questio ns/7804673/escaping-separator-in-double-quotes) – pfnuesel

+0

첫 번째 큰 따옴표로 묶인 섹션에 항상 쉼표가 두 개 있으면'cut -d ','-f1-3,5' – n0741337

답변

0

로 삼았 출력 :

awk -f getFields.awk input.txt 
input.txt 당신의 입력 파일입니다

getFields.awk은 다음과 같습니다

{ 
    split("",a) 
    splitLine() 
    print a[1],a[3] 
} 

function splitLine(s,indq,t,r,len) { 
# Assumptions: 
# * spaces before or after commas are ignored 
# * spaces at beginning or end of line is ignored 

# definition of a quoted parameter: 
# - starts with: (^ and $ are regexp characters) 
# a) ^" 
# b) ," 
# - ends with: 
# a) "$ 
# b) ", 

    s=$0; k=1 
    s=removeBlanks(s) 
    while (s) { 
     if (substr(s,1,1)=="\"") 
      indq=2 
     else { 
      sub(/[[:blank:]]*,[[:blank:]]*"/,",\"",s) 
      indq=index(s,",\"") 
      if (indq) { 
       t=substr(s,1,indq-1) 
       splitCommaString(t) 
       indq=indq+2 
      } 
     } 
     if (indq) { 
      s=substr(s,indq) 
      sub(/"[[:blank:]]*,/,"\",",s) 
      len=index(s,"\",") #find closing quote 
      if (!len) { 
       if (match(s,/"$/)) { 
        len=RSTART-1 
       } 
       else 
        len=length(s) 
       r=substr(s,1,len) 
       s="" 
      } else { 
       r=substr(s,1,len-1) 
       s=substr(s,len+2) 
      } 
      a[k++]=r 
     } else { 
      splitCommaString(s) 
      s="" 
     } 
    } 
    k=k-1 
} 

function splitCommaString(t,b,i) { 
    n=split(t,b,",") 
    for (i=1; i<=n; i++) 
     a[k++]=removeBlanks(b[i]) 
}  

function removeBlanks(r) { 
    sub(/^[[:blank:]]*/,"",r) 
    sub(/[[:blank:]]*$/,"",r) 
    return r 
} 
1

csv 파서를 사용하는 것이 좋습니다. 당신은 단지 수입에 그래서 예를 들어, 는 내장 모듈 하나를 가지고 그것을 :

import sys 
import csv 

with open(sys.argv[1], newline='') as csvfile: 
    csvreader = csv.reader(csvfile) 
    csvwriter = csv.writer(sys.stdout) 
    for row in csvreader: 
     csvwriter.writerow([row[e] for e in (0,2)]) 

귀하의 예제 라인을 가정하면 같은 스크립트 실행 infile라는 이름의 입력 파일에 있습니다

python3 script.py infile 

즉 수율 : 큰 따옴표 이스케이프 세퍼레이터 (

"dfjsdlfkj,fsdkfj,werkj",234234