假设我有这两个文件:
文件1:
1 2 3 4 5 6 7
文件2:
1
2
3
4
5
6
7
是否可以使用diff
来比较这两个文件,以便结果为equal
?
(如果不是,我应该使用哪些其他工具?)
由于
答案 0 :(得分:2)
你可以折叠空格,file2
看起来像file1
,每个数字在同一行:
$ cat file1
1 2 3 4 5 6 7
$ cat file2
1
2
4
3
5
6
7
$ diff <(echo $(< file1)) <(echo $(< file2))
1c1
< 1 2 3 4 5 6 7
---
> 1 2 4 3 5 6 7
说明:
< file # Equivalent to "cat file", but slightly faster since the shell doesn't
# have to fork a new process.
$(< file) # Capture the output of the "< file" command. Can also be written
# with backticks, as in `< file`.
echo $(< file) # Echo each word from the file. This will have the side effect of
# collapsing all of the whitespace.
<(echo $(< file)) # An advanced way of piping the output of one command to another.
# The shell opens an unused file descriptor (say fd 42) and pipes
# the echo command to it. Then it passes the filename /dev/fd/42 to
# diff. The result is that you can pipe two different echo commands
# to diff.
或者,您可能希望file1
看起来像file2
,每个数字都在不同的行上。这将产生更有用的差异输出。
$ diff -u <(printf '%s\n' $(< file1)) <(printf '%s\n' $(< file2))
--- /dev/fd/63 2012-09-10 23:55:30.000000000 -0400
+++ file2 2012-09-10 23:47:24.000000000 -0400
@@ -1,7 +1,7 @@
1
2
-3
4
+3
5
6
7
这类似于第一个命令,echo
更改为printf '%s\n'
以在每个单词后面添加换行符。
注意:如果要传播的文件过长,这两个命令都将失败。这是因为命令行长度的限制。如果发生这种情况,那么您需要解决此限制,例如将echo / printf的输出存储到临时文件中。
答案 1 :(得分:1)
有些差异有-b
(忽略空白)和-w
(ingnore whitespace),但由于unix实用程序都是面向行的,所以我不会将空格包括\n
字符。
Dbl - 检查您的diff
版本是否与diff --help | less
或man diff
没有任何奇特的gnu选项。
您的格式是否正确,文件1,数据全部在一行?您可以强制file2将该格式与
匹配awk '{printf"%s ", $0}' file2
或者如评论中所述,转换文件1
awk '{for (i=1;i<=NF;i++) printf("%s\n", $i)}' file1
但我猜你的数据并不那么简单。此外,当您最不能花时间处理它们时,可能会出现行长度限制。
可能不是你想听到的,diff
像源代码这样复杂的东西并不是一门精确的科学。因此,如果您仍然需要帮助,请创建一个稍微复杂的测试用例并将其添加到您的问题中。
最后,您需要向我们展示您期望这样的差异项目的输出看起来像什么。现在,我看不出任何有意义的方法来显示非繁琐案例的差异。 IHTH
答案 2 :(得分:1)
如果事实证明数据确实足够简单而不会遇到限制,并且文件之间的唯一区别是第一个按空格分隔而第二个按换行分隔,您也可以进行过程替换(如建议的那样)上面用sed用换行符替换第一个文件中的空格:
diff <(sed 's/ /\n/g' file1) file2