【问题标题】:How to use "grep -wvf" to get differences between two files如何使用“grep -wvf”来获取两个文件之间的差异
【发布时间】:2021-10-11 00:24:15
【问题描述】:

我有两个文件。

-> cat firstfile
sample-dev
sample-dev-auth

-> cat secondfile
sample-dev
sample-dev-auth
sample-dev-temp

然后我执行grep -wvf firstfile secondfile,我知道这会给我两个文件之间的差异,所以我认为输出将是sample-dev-temp,但没有

-> grep -wvf firstfile secondfile

什么都没有。

我尝试了grep -wf,它与-wvf相反,我虽然它会告诉我

sample-dev
sample-dev-auth

但还是不,就像

-> grep -wf firstfile secondfile

输出:

样本开发

sample-dev-auth

sample-dev-temp

它返回所有项目并突出显示相似的部分。

为什么会这样?以及如何得到我想要的结果?

【问题讨论】:

  • 您可能正在寻找commdiff,而不是grep
  • 试试grep -wvf secondfile firstfile
  • echo sample-dev-auth | grep -w sample-dev 打印出sample-dev-auth-w 选项查找单词边界,破折号是单词边界。所以firstfile 中的第一行必然会匹配secondfile 中的所有三行——因此不会打印任何内容。您需要一个具有不同“单词”定义的命令——或者可能使用-x(精确)匹配选项而不是-w。 (对grep -xvf firstfile secondfile 的随意实验会产生错误的结果;看起来并不那么容易。)

标签: linux shell command-line grep command


【解决方案1】:

命令grep -wf firstfile secondfilefirstfile 读取模式并在secondfile 中搜索它们。当我执行grep -wf firstfile secondfile 时,我得到以下输出:

sample-dev
sample-dev-auth
sample-dev-temp

请注意,我的输出与您的不同。让我用我的输出解释 grep 的行为。 在secondfile 中找到的模式(标记为粗体)都列在firstfile 中。这就是grep 的用途,搜索模式。

如果我们将参数-v 添加到 grep 命令,结果将被反转(按行)。这意味着将显示所有不匹配的行。因此我们有一个空结果,因为所有行都匹配。我们可以通过向secondfile 添加额外数据来验证这种行为,例如

$ echo hello >> secondfile 
$ grep -wvf firstfile secondfile
hello

只显示 hello,因为这里没有匹配 firstfile 中的模式。

话虽如此,grep 不是您在这种情况下应该使用的工具。您可以使用diff 工具来查找文件中的差异,例如:

$ diff firstfile secondfile
2a3
> sample-dev-temp

请看diff的手册。有很多自定义选项。

【讨论】:

    猜你喜欢
    • 2017-02-14
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    相关资源
    最近更新 更多