linux - shell脚本比较两个文件并将差异写入第三个文件

标签 linux shell

我想比较两个文件并将两个文件之间的差异重定向到第三个文件。
文件1:

  /opt/a/a.sql
  /opt/b/b.sql
  /opt/c/c.sql

如果任何文件在 /opt/c/c.sql 之前有 #,则应跳过 #

文件2:

 /opt/c/c.sql
 /opt/a/a.sql

我想知道两个文件之间的差异。在这种情况下,/opt/b/b.sql 应存储在不同的文件中。谁能帮助我实现上述场景?

最佳答案

文件1

$ cat file1 #both file1 and file2 may contain spaces which are ignored

/opt/a/a.sql
/opt/b/b.sql

/opt/c/c.sql
/opt/h/m.sql

文件2

$ cat file2
/opt/c/c.sql
/opt/a/a.sql

awk 'NR==FNR{line[$1];next} 
     {if(!($1 in line)){if($0!=""){print}}}
    ' file2 file1 > file3

文件3

$ cat file3
/opt/b/b.sql
/opt/h/m.sql

注释:

  1. 传递给 awk 的文件顺序在这里很重要,传递要检查的文件 - file2 这里 - 首先是主文件 -file1

  2. 检查awk documentation了解这里做了什么。

关于linux - shell脚本比较两个文件并将差异写入第三个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37187785/

相关文章:

linux - 如何让 cg_annotate 包含字典?

Linux 32位反汇编有下一个字节的调用指令

python - 使用子进程从 python 脚本编译 C++ 程序

linux - shell 导出变量没有生效

linux - 使用变量写入文件而不重复

c++ - CPack 具有自己依赖项的多个包

linux - Nginx(代理)+ Apache : two process listening same port

macos - Launchd 脚本正在运行但缺少输出(退出代码为 : 2)

c - 如何在Linux中查找执行文件?

node.js - 在 NodeJS 中运行 Conda 命令