gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:02:40 30 4
gpt4 key购买 nike

我想比较两个文件并将两个文件之间的差异重定向到第三个文件。
文件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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com