从文件一中排除与文件二相同的行并保留行顺序

Exclude from file one the lines in common with file two and preserve line order

一个

pl
a
ff
c
b
nn

两个

b
a
z
k
c
d

我想从第一个文件中删除第二个文件中的所有行(公共行)。我想保持 file_one 行顺序。

可以在逐行检查模式下工作,例如:

while read line; do
  if ! grep $line two; then
    echo $line >> one_only
  fi
done < one

但这可能不是快速检查的最佳选择。 另一种方法是对先前排序的文件使用“comm”命令:

comm -1 -2 <(sort one) <(sort two) \
  | tr '\n' '\|' \
  | sed 's/|/\|/g;s/\|$/\n/' \
  > common_lines

grep -v "$(cat common_lines)" one

第一个命令创建一个“逻辑或模式”:

a\|b\|c

可以与 grep 一起重复使用,以从“一个”文件中排除公共行。以这种方式保留了“一”行的原始顺序。结果将是:

pl
ff
nn

您能否提出任何其他想法来进一步减少计算时间?

真实的输入文件填充得更多并且包含短名称(软件名称):

blender
gimp
vim
emacs
mozilla-firefox
google-earth

等等...

使用two的线条作为模式,

grep -Fx -f two -v one
awk 'NR==FNR{a[[=10=]]; next} !([=10=] in a)' two one

关于您问题中的 while read 循环,请阅读 why-is-using-a-shell-loop-to-process-text-considered-bad-practice