gpt4 book ai didi

string - 空格/制表符/换行不敏感比较

转载 作者:行者123 更新时间:2023-11-29 09:49:03 24 4
gpt4 key购买 nike

假设我有这两个文件:

文件 1:1 2 3 4 5 6 7

文件 2:

1
2
3
4
5
6
7

是否可以使用diff 来比较这两个文件,使结果相等

(如果不能,我应该使用哪些其他工具?)

谢谢

最佳答案

您可以折叠空格,使 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 的输出存储到临时文件中。

关于string - 空格/制表符/换行不敏感比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12362347/

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