2

我有一个 .CSV 文件,其中几乎没有包含数字的记录,这些记录用双引号括起来(例如“455,365.44”),引号之间有逗号。我需要从记录的数值中删除逗号(“455,365.44”在处理后应该看起来像 455365.44),以便我可以在文件的进一步处理中使用它们。

这是文件的示例

column 1, column 2, column 3, column 4, column 5, column 6, column 7
12,"455,365.44","string with quotes, and with a comma in between","4,432",6787,890,88
432,"222,267.87","another, string with quotes, and with two comma in between","1,890",88,12,455
11,"4,324,653.22","simple string",77,777,333,22

我需要结果如下:

column 1, column 2, column 3, column 4, column 5, column 6, column 7
12,455365.44,"string with quotes, and with a comma in between",4432,6787,890,88
432,222267.87,"another, string with quotes, and with two comma in between",1890,88,12,455
11,4324653.22,"simple string",77,777,333,22

PS:我只需要像这样转换数字的值,字符串值应该保持不变。

请帮忙...

4

1 回答 1

4

要删除引号(用没有引号的数字替换带有引号的数字):

s/"(\d[\d.,]*)"/\1/g

红字

对于逗号,如果您的正则表达式实现支持,我只能考虑向前和向后看(如果前后是引号内的数字,则将逗号替换为空):

s/(?<="[\d,]+),(?=[\d,.]+")//g

您必须在删除引号之前执行此操作。

它也可能在没有后视的情况下工作:

s/,(?=[\d,.]*\d")//g

红字

在 shell 脚本中,您可能需要使用perl ,例如执行:

cat test.csv | perl -p -e 's/,(?=[\d,.]*\d")//g and s/"(\d[\d,.]*)"/\1/g'

正则表达式的解释:

首先执行:

s/,(?=[\d,.]*\d")//g 

这将删除所有后跟数字 ( [\d,.]*\d) 和引号的逗号,从而仅删除引号内数字中的逗号

下一个执行

s/"(\d[\d,.]*)"/\1/g

这将用不带引号的值替换引号内的所有数字

于 2013-09-04T22:36:54.863 回答