[英]Print differences between two files under Linux
I'm generating snapshot files from my system which contains user rights to directories (short example below): 我正在从系统中生成快照文件,该文件包含对目录的用户权限(以下简短示例):
first_snapshot first_snapshot
RO_sad;user_a
RW_sad;user_b
RO_5ka;user_c
RO_wts;user_c
After few moments I get another snapshot which contains as follows: 片刻之后,我得到另一个包含以下内容的快照:
second_snapshot second_snapshot
RW_sad;user_a
RW_sad;user_b
RO_5ka;user_c
Note that rights has changed for user a (from RO to RW) and for user c (rights RO_wts were removed). 请注意,用户a (从RO到RW)和用户c (权利RO_wts已删除)的权限已更改。 How can i print differences between those two files? 如何打印这两个文件之间的差异? When using 使用时
diff first_snapshot second_snapshot
i get something like this: 我得到这样的东西:
1,4c1,3
< RO_sad;user_a
< RW_sad;user_b
< RO_5ka;user_c
< RO_wts;user_c
\ No newline at end of file
---
> RW_sad;user_a
> RW_sad;user_b
> RO_5ka;user_c
\ No newline at end of file
Desired file that would help me should look like: 对我有帮助的所需文件应如下所示:
remove RO_sad;user_a
add RW_sad;user_a
remove RO_wts;user_c
Any ideas how could i achieve that? 任何想法我怎么能做到这一点? I'd prefer using diff but I need to remove entries that doesnt matter for me, like RW_sad;user_b (exists in both snapshots) or all addons from diff. 我更喜欢使用diff,但是我需要删除对我来说无关紧要的条目,例如RW_sad; user_b(两个快照中都存在)或diff中的所有插件。
You want a "unified diff" like this: 您需要这样的“统一差异”:
diff -U0 f1.txt f2.txt
It will give you something like this: 它会给你这样的东西:
--- f1.txt 2014-10-09 19:47:33.000000000 +0800
+++ f2.txt 2014-10-09 19:47:44.000000000 +0800
@@ -1 +1 @@
-RO_sad;user_a
+RW_sad;user_a
@@ -4 +3,0 @@
-RO_wts;user_c
You can then replace the first characters with sed: 然后,您可以用sed替换前几个字符:
diff -U0 f1.txt f2.txt | sed -n -e 's/^+R/add /p' -e 's/^-R/remove /p'
This gives you: 这给您:
remove O_sad;user_a
add W_sad;user_a
remove O_wts;user_c
Try diff -u 尝试diff -u
- RO_sad;user_a
+ RW_sad;user_a
- RO_wts;user_c
@John @约翰
Not quite. 不完全的。 When using diff -U0 i get: 当使用diff -U0时,我得到:
--- first_snapshot 2014-10-09 14:02:27.000000000 +0200
+++ second_snapshot 2014-10-09 14:02:27.000000000 +0200
@@ -1,4 +1,3 @@
-RO_sad;user_a
-RW_sad;user_b
-RO_5ka;user_c
-RO_wts;user_c
\ No newline at end of file
+RW_sad;user_a
+RW_sad;user_b
+RO_5ka;user_c
\ No newline at end of file
So i still get this line 所以我仍然得到这条线
+RW_sad;user_b
plus entries 加上条目
\ No newline at end of file
I've managed to remove duplicated values from both files using AWK 我设法使用AWK从两个文件中删除了重复的值
awk 'FNR==NR{a[$1];next};!($1 in a)' $first $second > $third
awk 'FNR==NR{a[$1];next};!($1 in a)' $second $first > $fourth
and then when using diff 然后当使用差异
diff -uU0 $fourth $third > diff.txt
I get something I could work with: 我得到一些我可以使用的东西:
--- fourth 2014-10-09 14:21:07.000000000 +0200
+++ third 2014-10-09 14:21:07.000000000 +0200
@@ -1,2 +1 @@
-RO_sad;user_a
-RO_wts;user_b
+RW_sad;user_a
Using sed on diff.txt gives me all I need :) 在diff.txt上使用sed满足了我的所有需求:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.