NIT*_*JAN 4 shell-script text-processing cut
我想从文件中提取一些列并粘贴到另一个文件中。我目前正在使用:
cat $Input_file | cut -f$Var_ColumnNo1,$Var_ColumnNo2,$Var_ColumnNo1 -d"," > $OUTPUT_file
Run Code Online (Sandbox Code Playgroud)
但是这个命令在大文件上花费了很多时间(例如,在一个 50 MB 的文件上,它大约需要 2 秒),并且使我的脚本非常慢,因为我需要多次运行这个操作。
有没有什么有效的方法可以做到这一点?
不是真的,不是。cut
几乎可以肯定是最快的方法。我在 157M 文件上测试了一些替代方案,cut
显然是最快的(顺便说一下,cat
这里不需要):
$ time cut -f 2,6,8 -d ',' file > /dev/null
real 0m0.859s
user 0m0.803s
sys 0m0.053s
$ time awk -F, '{print $2,$6,$8}' file > /dev/null
real 0m5.442s
user 0m5.317s
sys 0m0.050s
$ time perl -F, -lane 'print "@F[1,5,7]"' file > /dev/null
real 0m6.065s
user 0m5.943s
sys 0m0.070s
Run Code Online (Sandbox Code Playgroud)
如果你想加快速度,你需要改变你的脚本正在做什么。我建议你再问一个问题,包括你输入文件的一个例子,并解释你的最终目标是什么。如果您“需要多次运行此操作”,那么您几乎肯定做错了。只要有可能,您的输入文件应该只读取一次。