【问题标题】:Extract modified and added lines from two csv files using shell or diff command使用 shell 或 diff 命令从两个 csv 文件中提取修改和添加的行
【发布时间】:2012-08-22 17:56:21
【问题描述】:

我有两个 csv 文件 F1 和 F2 的行顺序相同,我想通过比较 F2 中的文件 F1 和 F2 来提取更改/添加的行。

我尝试了 diff 命令,但我可以看到变化。我如何读取模式并从 F2 中提取线条?

F1(文件 1):

1234,Joe,pieter,joe@gmail.com,male,22
1235,Shally,Jonse,shally@yahoo.com,female,24
1235,Harry,poter,harry@gmail.com,male,21
1235,Helen,Jairag,helen@gmail.com,female,21
2585,Dinesh,Jairag,helen@gmail.com,female,21

F2(文件 2):

1234,Joe,pieter,joe@gmail.com,male,22
1235,Shally,Jonse,shally@yahoo.com,female,24
1235,Harry,Potter,harry@gmail.com,male,21
1235,Helen,Jairag,helen@gmail.com,female,21

执行的命令:

diff F2 F1

输出:

3c3
< 1235,Harry,Potter,harry@gmail.com,male,21
---
> 1235,Harry,poter,harry@gmail.com,male,21
4a5
> 2585,Dinesh,Jairag,helen@gmail.com,female,21

文件 F3 中的预期输出:

1235,Harry,poter,harry@gmail.com,male,21
2585,Dinesh,Jairag,helen@gmail.com,female,21

【问题讨论】:

  • 你的问题不是很清楚,能不能加上预期的输出?
  • 感谢我添加了预期的输出,

标签: linux bash shell diff


【解决方案1】:
diff --changed-group-format='%<' --unchanged-group-format='' file1 file2

【讨论】:

  • 谢谢,它有助于提取行并写入新文件
【解决方案2】:

我了解到您想从 File2 中提取更改/添加的行!
因此,在您的示例中,File2 中只有一个更改的行,而 File2 中没有添加的行。
diff 的基本调用模式是 diff old new,输出告诉您需要做什么来更新 old。因此,要了解 File2 的不同之处,您可以将其用作第二个参数。我建议使用-u 选项到diff。这为您提供了 File2 中需要在 File1 中更改/添加的每一行,并在第一个位置中使用 +

diff -u File1 File2

给予

--- File1   2012-08-22 11:30:07.000000000 +0200
+++ File2   2012-08-22 11:30:25.000000000 +0200
@@ -1,5 +1,4 @@
 1234,Joe,pieter,joe@gmail.com,male,22
 1235,Shally,Jonse,shally@yahoo.com,female,24
-1235,Harry,poter,harry@gmail.com,male,21
+1235,Harry,Potter,harry@gmail.com,male,21
 1235,Helen,Jairag,helen@gmail.com,female,21
-2585,Dinesh,Jairag,helen@gmail.com,female,21

现在只过滤除前两个以​​外的以+ 开头的行:

diff -u data1 data2 | \
  awk 'NR > 2 && $0 ~ /^+/ {print substr($0,2)}'

1235,Harry,Potter,harry@gmail.com,male,21

或者反过来:

diff -u data2 data1 | \
  awk 'NR > 2 && $0 ~ /^+/ {print substr($0,2)}'

1235,Harry,poter,harry@gmail.com,male,21
2585,Dinesh,Jairag,helen@gmail.com,female,21

【讨论】:

  • 感谢 Theodros,此解决方案也帮助解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多