Issue
How can I diff two (or more) files, displaying the file name at the beginning of each line?
That is, instead of this:
--- file1.c
+++ file2.c
@@ -1 +1 @@
-int main() {
+int main(void) {
I would prefer something like this:
file1.c:- int main() {
file2.c:+ int main(void) {
This is not so useful when there are only two files, but extremely handy when using --from-file
/--to-file
.
Solution
I could not find a more concise solution, so I wrote my own script to do it, using several calls to diff
to add a different prefix each time.
#!/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
Answered By - anol Answer Checked By - Clifford M. (WPSolving Volunteer)