带有前缀每行的文件名的diff

时间:2015-03-04 14:56:53

标签: shell diff

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

即代替:

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

我更喜欢这样的事情:

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

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

1 个答案:

答案 0 :(得分:0)

我找不到更简洁的解决方案,因此我编写了自己的脚本来执行此操作,使用多次调用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