【问题标题】:shell script to compare two files and write the difference to third file用于比较两个文件并将差异写入第三个文件的 shell 脚本
【发布时间】:2025-12-11 01:40:01
【问题描述】:

我想比较两个文件并将两个文件之间的差异重定向到第三个文件。
文件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 应该存储在不同的文件中。谁能帮我实现上述场景?

【问题讨论】:

  • 首先你应该决定你想使用三个中的哪一个:批处理、powershell 或 shell 脚本
  • 其次,您应该研究一下您将使用哪些命令来选择脚本语言。
  • 我尝试了 diff 文件 file2,但没有得到预期的结果,我只需要 /opt/b/b.sql 作为输出......这可能吗?如果可能的话,任何人都可以帮助我...

标签: linux shell


【解决方案1】:

文件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. 查看awkdocumentation 了解这里做了什么。

【讨论】:

    【解决方案2】:

    您可以使用catsedsortuniq 等工具。

    主要观察结果是:如果该行在两个文件中,那么它在cat file1 file2不是唯一的

    此外,在cat file1 file2| sort 中,所有双打都是按顺序排列的。使用uniq -u,我们得到独特的线条并拥有这个管道:

    cat file1 file2 | sort | uniq -u 
    

    使用sed 删除前导空格、空行和注释行,我们得到了这个最终管道:

    cat file1 file2 | sed -r 's/^[ \t]+//; /^#/ d; /^$/ d;' | sort | uniq -u > file3
    

    【讨论】: