重定向并保持diff + bash输出的格式

时间:2015-01-29 23:09:36

标签: bash diff

我有这两个文件file1.txt

$ cat file1.txt
I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples.
I need to run the laundry.
I need to wash the dog.
I need to get the car detailed.

和file2.txt

$ cat file2.txt
I need to buy apples.
I need to do the laundry.
I need to wash the car.
I need to get the dog detailed.

我希望使用diff命令查看文件的差异,并使用-y选项显示它。

$ diff --width=250 -y file1.txt file2.txt
I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples.               |   I need to buy apples.
I need to run the laundry.                                                                                                  |   I need to do the laundry.
I need to wash the dog.                                                                                                     |   I need to wash the car.
I need to get the car detailed.                                                                                             |   I need to get the dog detailed.

我希望能够重定向上面diff的输出,但我想保持上面的格式。

我在做这件事时遇到了麻烦。可以吗?

$ echo $(diff --width=250 -y file1.txt file2.txt)
I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples. | I need to buy apples. I need to run the laundry. | I need to do the laundry. I need to wash the dog. | I need to wash the car. I need to get the car detailed. | I need to get the dog detailed.

我还想知道file1.txt中最长行中有多少个字符(包括空格)。 我尝试过以下但没有快乐。可以这样做吗?

$ wc -L file1.txt
109 file1.txt

1 个答案:

答案 0 :(得分:0)

要确保有足够的空间来完整显示所有行,请使用:

diff --width=$(( $(cat file1.txt file2.txt|wc -L)*2+3 )) -y file1.txt file2.txt

有人可能天真地认为diff所需的宽度与每个文件中最大行长度的总和有关。事实并非如此。

要在使用echo时保留换行符,需要使用双引号:

$ echo "$(diff --width=$(( $(cat file1.txt file2.txt|wc -L)*2+3 )) -y file1.txt file2.txt)"
I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples. I need to buy apples. | I need to buy apples.
I need to run the laundry.                                                                                    | I need to do the laundry.
I need to wash the dog.                                                                                       | I need to wash the car.
I need to get the car detailed.                                                                               | I need to get the dog detailed