2

I have two files and a shell script.

File 1:

Batman
Superman
John Snow
Jack Sparrow
Rob Stark

File 2:

Batman
Ironman
Superman
Spiderman
John Snow
Arya Stark
Jack Sparrow
Rob Stark
The hound

Script:

#!/bin/bash

sort ~/Desktop/file1.txt > ~/Desktop/fileA.txt
sort ~/Desktop/file2.txt > ~/Desktop/fileB.txt
diff -y ~/Desktop/fileA.txt ~/Desktop/fileB.txt > ~/Desktop/diff.txt

The script runs absolutely fine, the output is:

                                  > Arya Stark
Batman                              Batman
                                  > Ironman
Jack Sparrow                        Jack Sparrow
John Snow                           John Snow
Rob Stark                           Rob Stark
                                  > Spiderman
Superman                            Superman
                                  > The hound

But I want to output to automatically be:

File A                               File B
                                  > Arya Stark
Batman                              Batman
                                  > Ironman
Jack Sparrow                        Jack Sparrow
John Snow                           John Snow
Rob Stark                           Rob Stark
                                  > Spiderman
Superman                            Superman
                                  > The hound

Whats the best way to so it using diff command only?

1 Answer 1

3

There are various improvements you could make to your approach but, keeping everything the same, all you need is to add one more line to your script and then make the last line append (>>) instead of overwrite:

#!/bin/bash

echo -e "FileA\t\t\t\t\t\t\t\tFileB" > diff.txt
sort ~/Desktop/file1.txt > ~/Desktop/fileA.txt
sort ~/Desktop/file2.txt > ~/Desktop/fileB.txt
diff -y ~/Desktop/fileA.txt ~/Desktop/fileB.txt >> ~/Desktop/diff.txt

A better way to write this would be

#!/usr/bin/env bash

file1="$1"
file2="$2"

printf "%-36s%36s\n" "FileA" "FileB"
diff -y <(sort "$file1") <(sort "$file2")

And then run with:

script.sh file1.txt file2.txt > diff.txt

This avoids creating unnecessary temporary files and does not require the file names to be hardcoded into the script.

Alternatively, if you want the actual file names to be shown, change the printf call above to

printf "%-36s%36s\n" "$file1" "$file2"
1
  • Also use colordiff, it's fancier :).
    – polym
    Jun 19, 2014 at 15:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .