2011-11-21 58 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" 
相关问题