在比较两个文件的结果中获取第二个文件的唯一行

anl*_*rye 7 command-line bash text-processing

我有两个文本文件,我想逐行读取 file1,在 file2 中搜索同一行并将其从 file2 中删除。

我有以下伪代码:

for line in file1.txt
do
  sed search line and delete in file2.txt
done
Run Code Online (Sandbox Code Playgroud)

小智 8

您可以使用 grep 完成此操作。

下面是一个例子:

$ echo localhost > local_hosts

$ grep -v -f local_hosts /etc/hosts
127.0.1.1       ubuntu

# The following lines are desirable for IPv6 capable hosts
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
Run Code Online (Sandbox Code Playgroud)

  • 更重要的是,您*应该*使用grep完成此操作。`file1` 中一行中的正则表达式特殊字符会导致 `sed` 出现很多问题,但是 `grep` 有 `-F` 来解决这个问题。 (4认同)

αғs*_*нιη 5

通常,您希望保留file2中实际上不在 file1 中的行。

这些还有更多的可能,

comm <(sort file1) <(sort file2) -23
Run Code Online (Sandbox Code Playgroud)

通过加入

join -v 1 <(sort file1) <(sort file2)
Run Code Online (Sandbox Code Playgroud)

或通过不需要对文件进行排序的AWK

awk 'NR==FNR{lines[$0];next} !($0 in lines)' file2 file1
Run Code Online (Sandbox Code Playgroud)