diff 文件名在每行前

diff with file names prefixing each line

如何区分两个(或更多)文件,在每行的开头显示文件名?

也就是说,而不是这个:

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

我更喜欢这样的东西:

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

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

我找不到更简洁的解决方案,所以我编写了自己的脚本来完成,多次调用 diff 每次添加不同的前缀。

#!/bin/bash

# the first argument is the original file that others are compared with
orig=
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