2011-11-21 61 views
4

我已經從數據庫中導出了一個CSV文件。某些字段是較長的文本塊,可以包含換行符。從這個文件中只刪除換行符中的新行,但保留所有其他行爲的最簡單方法是什麼?如何從文件中所有引用的文本中刪除換行符?

我不在乎它是否使用Bash命令行一個班輪或簡單的腳本,只要它工作。

例如,

"Value1", "Value2", "This is a longer piece 
    of text with 
    newlines in it.", "Value3" 
"Value4", "Value5", "Another value", "value6" 

較長一段文字的內部的換行應被刪除,但不是換行分離兩行。

+1

可以val你包含逃脫的報價? –

回答

6

在Python:

import csv 
with open("input.csv", "rb") as input, open("output.csv", "wb") as output: 
    w = csv.writer(output) 
    for record in csv.reader(input): 
     w.writerow(tuple(s.remove("\n") for s in record)) 
+0

+1使用csv模塊解析CSV文件。 –

+1

@MarkByers:謝謝。我認爲這比使用正則表達式很容易處理引用更多[可配置](http://docs.python.org/library/csv.html#csv.Dialect.doublequote)。 –

7

下面是一個Python的解決方案:

import re 
pattern = re.compile(r'".*?"', re.DOTALL) 
print pattern.sub(lambda x: x.group().replace('\n', ''), text) 

看到它聯機工作:ideone

2

這是非常簡單的,但你可能工作:

# cat <<\! | sed ':a;/"$/{P;D};N;s/\n//g;ba'        
> "Value1", "Value2", "This is a longer piece 
>  of text with 
>  newlines in it.", "Value3" 
> "Value4", "Value5", "Another value", "value6" 
> ! 
"Value1", "Value2", "This is a longer piece of text with newlines in it.", "Value3" 
"Value4", "Value5", "Another value", "value6" 
相關問題