8

如何替换大文件(> 100MB)中的所有行尾?我试过做

:%s/\n/, /g

但它太慢了。

4

6 回答 6

8

因此,我通过并测试/计时了其他人给出的一些答案,以及我自己的 python 答案。这是我得到的:

tr:

> time tr "\n" "," < lines > line
real    0m1.617s
user    0m0.100s
sys     0m1.520s

Python:

> time python -c 'import sys; print sys.stdin.read().replace("\n",", "),' < lines > line
real    0m1.663s
user    0m0.060s
sys     0m1.610s

awk:

> time awk '{printf("%s, ", $0)}' lines > line                                 
real    0m1.998s
user    0m0.390s
sys     0m1.600s

perl:

> time perl -e 'while (<>) { chomp; print "$_, " }' lines > line
real    0m2.100s
user    0m0.590s
sys     0m1.510s

赛德:

> time sed 's/$/, /g' lines > line                                             
real    0m6.673s
user    0m5.050s
sys     0m1.630s

这是我使用的文件:

> ls -lh lines
-rw-r--r-- 1 some one 101M 2010-03-04 19:54 lines
> wc -l < lines
1300000
> head -n 3 < lines
The pretty pink puma pounced on the unsuspecting aardvark, the scientist watched.
The pretty pink puma pounced on the unsuspecting aardvark, the scientist watched.
The pretty pink puma pounced on the unsuspecting aardvark, the scientist watched.
> head -n 1 < lines | wc -c
82

最初的时间安排是在 cygwin 中进行的,现在已经在完全更新的 ubuntu 9.10 中进行了。此外,文本文件的大小增加到 100 兆,行数为 80 个字符宽。正如你所看到的,除了 sed 之外的任何东西都是一个好主意。

于 2010-03-05T00:46:11.643 回答
3

:%s/$/, /后面跟着一个:1,$j可能会更快。否则,请在外部实用程序中执行此操作:

perl -e 'while (<>) { chomp; print "$_, " }' input_file > output_file

awk '{printf("%s, ", $0)}' input_file > output_file

我不知道哪个会最快。

于 2010-03-04T14:42:59.703 回答
2

使用这个 Perl 脚本来检查你的文件;它比使用 VIM 将所有内容保存在内存中要快。只需将输出通过管道传输到新文件。

#!/usr/local/bin/perl

while (<>) {
  $_ =~ s/\n/,/g;
  print $_;
}
于 2010-03-04T14:40:51.203 回答
0

你必须在vim中这样做吗?

有一个很好的 Unix 实用程序可以进行基于字符的翻译。它被称为tr。一些参考

在您的情况下,它将是:

tr "\n" "," < 输入文件 > 输出文件
于 2010-03-04T14:40:53.547 回答
0
$ more file
aaaa
bbbb
cccc
dddd
eeee

$ awk 'NR>1{printf("%s, ", p)}{p=$0}END{print p}' file
aaaa, bbbb, cccc, dddd, eeee

$ sed -e :b -e '$!N;s/\n/, /;tb' file
于 2010-03-04T15:06:10.190 回答
0

最好的工具是 sed,您可以将它与 :! 命令

所以用:!sed -e 's/\n/,/g' % > %.tmp ; cat %.tmp > % ; rm %.tmp'

在集成到当前文件之前,您需要创建一个带有更改的 tmp 文件

于 2010-03-04T17:16:11.467 回答