我正在尝试将新文件(例如new.txt
)与旧文件(例如old.txt
)进行比较,以查看新文件中添加的内容。我正在尝试将新添加的信息添加到名为 的新文件中,newCourses.txt
并将修改后的信息添加到modifiedCourses.txt
.如果通过 diff 无法做到这一点,那么在不安装软件包或软件的情况下有哪些替代方案?
old.txt
2016 2BUSI 4850 K002 BUSINESS MW 02:10P-09:30P
2016 2BUSI 4840 K002 PRESPECH MW 07:10P-09:30P
2016 2BUSI 4820 K002 SCHLOFSC MW 07:10P-09:30P
2016 2BUSI 4870 K002 HISTORYZ MW 04:10P-09:30P
new.txt
2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P
2016 2BUSI 4840 K002 PRESPECH MW 07:10P-09:30P
2016 2BUSI 4820 K002 SCHLOFSC MF 07:10P-09:30P
2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P
2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55P
我这样做时的输出diff old.txt new.txt
:
1c1
< 2016 2BUSI 4850 K002 BUSINESS MW 02:10P-09:30P
---
> 2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P
3,4c3,5
< 2016 2BUSI 4820 K002 SCHLOFSC MW 07:10P-09:30P
< 2016 2BUSI 4870 K002 HISTORYZ MW 04:10P-09:30P
\ No newline at end of file
---
> 2016 2BUSI 4820 K002 SCHLOFSC TF 07:10P-09:30P
> 2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P
> 2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55P
\ No newline at end of file
我如何将它输出到两个不同的文件,例如
newCourses.txt
包含
2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55P
并且modifiedCourses.txt
将包含
2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P
2016 2BUSI 4820 K002 SCHLOFSC TF 07:10P-09:30P
2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P
答案1
你可以使用awk
:
awk 'NR==FNR{ z[$5]=$0; next}{ if ($5 in z){ if ($0!=z[$5]){
print >"modifiedCourses.txt"}} else { print >"newCourses.txt"}}' old.txt new.txt
这会将old.txt
行读取并保存到数组中(索引是课程的名称),然后读取new.txt
并针对每个课程检查它是否是数组的索引:如果是,则检查该行是否已更改,如果是它将其打印到modifiedCourses.txt
;如果不是索引,它会将行打印为newCourses.txt
You can change $0
to $7
if the only change of important is the hours.