在每行前缀上文件名的diff差异

4

我能如何比较两个(或多个)文件,并在每行开头显示文件名?

也就是说,不是这样:

--- file1.c
+++ file2.c
@@ -1 +1 @@
-int main() {
+int main(void) {

我更喜欢这样的东西:
file1.c:- int main() {
file2.c:+ int main(void) {

如果只有两个文件,这并不是很有用,但使用--from-file/--to-file时非常方便。

2个回答

2

我没有找到更为简洁的解决方案,所以我编写了自己的脚本来实现它,使用多个 diff 调用每次添加不同的前缀。

#!/bin/bash

# the first argument is the original file that others are compared with
orig=$1
len1=${#1}
shift

# we compute the length of the filenames to ensure they are aligned
for arg in "$@"
do
    len2=${#arg}
    maxlen=$((len1 > len2 ? len1 : len2))
    prefix1=$(printf "%-${maxlen}s" "$orig")
    prefix2=$(printf "%-${maxlen}s" "$arg")
    diff --old-line-format="$prefix1:-%L" \
         --new-line-format="$prefix2:+%L" \
         --unchanged-line-format="" $orig $arg
    echo "---" # not necessary, but helps visual separation
done

0

通过添加更多的格式,如组格式,并将文件名作为顶部标题打印,改进了上述脚本,这是基本需求,特别是当我们递归地在几个子目录上运行diff时。还添加了diff -rwbit以忽略空格等。如果您不需要,请删除此选项-wbit。保持无害的-r。

我经常与git一起使用,如下所示:git difftool -v -y -x mydiff

+ cat mydiff
#!/usr/bin/bash
# the first argument is the original file that others are compared with
orig=$1
len1=${#1}
shift

# we compute the length of the filenames to ensure they are aligned
for arg in "$@"
do
    len2=${#arg}
    maxlen=$((len1 > len2 ? len1 : len2))
    prefix1=$(printf "%-${maxlen}s" "$orig")
    prefix2=$(printf "%-${maxlen}s" "$arg")
    echo -e "\nmydiff $orig $arg =========================\n"
    diff -rwbit \
         --old-line-format="$prefix1:-%L" \
         --new-line-format="$prefix2:+%L" \
     --old-group-format='%df%(f=l?:,%dl)d%dE
%<' \
         --new-group-format='%dea%dF%(F=L?:,%dL)
%>' \
         --changed-group-format='%df%(f=l?:,%dl)c%dF%(F=L?:,%dL)
%<---
%>' \
         --unchanged-line-format="" $orig $arg
    echo "---" # not necessary, but helps visual separation
done
+ cat -n test1
     1  1st line in test1
     2  2nd line in test1
     3  3rd line in test1
     4  4th line in test1
     5  6th line in test1
+ cat -n test2
     1  1st line in test1
     2  2nd line in test2 changed
     3  3rd line added in test2
     4  4th line in test1
+ mydiff test1 test2

mydiff test1 test2 =========================

2,3c2,3
test1:-2nd line in test1
test1:-3rd line in test1
---
test2:+2nd line in test2 changed
test2:+3rd line added in test2
5d4
test1:-6th line in test1
---

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接