我有这个 csv 文件,这里是纯文本:http: //pastie.org/1425970
它在 excel 中的样子:http: //cl.ly/3qXk
我希望它看起来像的一个例子(仅以第一行为例):http ://cl.ly/3qYT
第一行纯文本:http: //pastie.org/1425979
我需要创建一个 csv 文件,将所有信息导入数据库表。
我可以手动创建 csv,但我想看看是否可以使用 textwrangler (grep) 查找和替换中的正则表达式来完成此操作
我有这个 csv 文件,这里是纯文本:http: //pastie.org/1425970
它在 excel 中的样子:http: //cl.ly/3qXk
我希望它看起来像的一个例子(仅以第一行为例):http ://cl.ly/3qYT
第一行纯文本:http: //pastie.org/1425979
我需要创建一个 csv 文件,将所有信息导入数据库表。
我可以手动创建 csv,但我想看看是否可以使用 textwrangler (grep) 查找和替换中的正则表达式来完成此操作
正则表达式并不是实现这一目标的最佳方式。正如其他人所指出的,您最好编写一些代码将文件解析为您想要的格式。
话虽如此,这个丑陋的正则表达式应该让你走到一半:
寻找:
(\d+),"?(?:(\d+),? ?)?(?:(\d+),? ?)?(?:(\d+),? ?)?(?:(\d+),? ?)?(?:(\d+),? ?)?(?:(\d+),? ?)?(?:(\d+),? ?)?"?
代替:
\1,\2\r\1,\3\r\1,\4\r\1,\5\r\1,\6\r\1,\7\r\1,\8
这将为您留下一些额外的行,如下所示:
1,1
1,8
1,11
1,13
1,
1,
1,
2,10
2,11
2,12
2,
2,
...
您可以手动清理多余的行,也可以使用以下正则表达式:
寻找:
\d+,\r
代替:
(empty string)
使用 Perl,您可以执行以下操作:
open(my $read,"<","input.csv") or die ("Gah, couldn't read input.csv!\n");
open(my $write,">","output.csv") or die ("WHAAAARGARBL!\n");
while(<$read>)
{
chomp;
if(/(\d+),"(.*)"/)
{
my @arr=split(/,/,$2);
foreach(@arr)
{
print $write $1.",".$2."\n";
}
}
}
close($read);
close($write);
不知道文友。但总的来说,我可以用伪代码描述这样做需要什么。
loop, read each line
strip off the newline
split into an array using /[, "]+/ as delimeter regex
loop using result. an array slice from element 1 to the last element
print element 0, comma, then itterator value
end loop
end loop
在 Perl 中,类似这样的..
while ($line = <DATA> ) {
chomp $line;
@data_array = split /[, "]+/, $line;
for $otherfield ( @data_array[ 1 .. $#data_array ]) {
print "$data_array[0], $otherfield\n";
}
}
如果您具有拆分功能,这应该很容易。