如何替换大文件(>100MB)中的所有行尾符?
我尝试过执行以下命令:
:%s/\n/, /g
但速度太慢了。
如何替换大文件(>100MB)中的所有行尾符?
我尝试过执行以下命令:
:%s/\n/, /g
但速度太慢了。
所以,我经过测试和计时一些其他人给出的答案,还有自己的一个Python答案。这是我的结果:
> 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
sed:
> 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之外,几乎任何其他东西都是一个好主意。
:%s/$/, /
后跟 :1,$j
可能更快。否则,可以使用外部实用程序进行操作:
perl -e 'while (<>) { chomp; print "$_, " }' input_file > output_file
awk '{printf("%s, ", $0)}' input_file > output_file
我不知道哪个最快。
在头脑中没有想到最快的方法。perl -ne 'chomp; print "$_, "' file
。 -n
"假设while循环"。 - ghostdog74#!/usr/local/bin/perl
while (<>) {
$_ =~ s/\n/,/g;
print $_;
}
$_
除了最后一个字符外不能有换行符 - chomp
可能会更快。 - Cascabel你必须在vim中完成这个吗?
有一个很好的Unix实用程序可以进行基于字符的转换。它叫做tr
。
一些参考资料。
在你的情况下,应该是这样的:
tr "\n" "," < input_file > output_file
tr
来实现这一点,有吗? - Cascabel最好的工具是sed,你可以使用它与:!命令一起使用
所以使用:!sed -e 's/\n/,/g' % > %.tmp ; cat %.tmp > % ; rm %.tmp'
在将其集成到当前文件之前,您需要创建一个带有更改的临时文件
$ 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