【问题标题】:Fast way to delete pattern lines from a file in shell从 shell 中的文件中删除模式线的快速方法
【发布时间】:2020-09-24 08:39:09
【问题描述】:

我有一个大约 60000 行的 file1,一个大约 20000 行的 file2。我需要从 file1 中删除 file2 中存在的行。 File2 还包含 .* 以从 file1 中删除类似的模式。

文件1:

ABC DEG
bhdh jdjjd
cdhhd jdjd
ABC hjj

文件2:

ABC.*
cdhhd jdjd

输出应该是:

bhdh jdjjd

现在,我正在使用下面的代码。

while read -r line
do
  sed -i "/${line}/d" $file1
done < "$file2" 

使用此代码,大约需要 30 分钟才能获得输出。我真的需要一种更好的方法来从 file1 中删除这些行。

【问题讨论】:

  • 类似于 grep 的答案,您可以使用 rg -vf file2 file1 以获得更快的速度(rg 是 github.com/BurntSushi/ripgrep)...如果 .* 是您打算使用的正则表达式的范围,@从 file2 中删除 .* 后,987654328@ 和 rg -vFf 会更快

标签: linux performance shell unix grep


【解决方案1】:

这正是你的任务:

grep -vf file2 file1

-v 将排除 file1 中与 file2 中的任何模式匹配的行


注意:您的循环非常慢,因为您使用 bash 循环逐行读取模式文件,并执行数千个 sed 命令,每个模式一个。另请参阅 here 了解为什么这是一种不好的做法。


注意:用上述命令的输出替换 file1:

grep -vf file2 file1 > file1.tmp && mv file1.tmp file1

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多