What is an easy way to do a sorted diff between two files?

UnixShell

Unix Problem Overview


I have two files in which some of the lines have changed order. I would like to be able to compare these.

One website suggested something that looks like this:

diff <(sort text2) <(sort text1)

But this yields the error: Missing name for redirect.

I am using tcsh. Is the command above for a different shell?

Is there a better way?

Unix Solutions


Solution 1 - Unix

This redirection syntax is bash specific. Thus it won't work in tcsh.

You can call bash and specify the command directly:

bash -c 'diff <(sort text2) <(sort text1)'

Solution 2 - Unix

Here's a function for it:

function diffs() {
        diff "${@:3}" <(sort "$1") <(sort "$2")
}

Call it like this:

diffs file1 file2 [other diff args, e.g. -y]

Presumably you could alter it as per David Schmitt's answer if necessary.

Solution 3 - Unix

> Is there a better way?

Yes, there is.

Use comm utility:

> usage: comm [-123i] file1 file2

Solution 4 - Unix

If this does not work for your shell, just do it in 3 lines:

sort text1 > text1.sorted
sort text2 > text2.sorted
diff text1.sorted text2.sorted

Simple but should work...

Solution 5 - Unix

The problem with your posted 'diff' is that diff can only receive one file via stdin. So I think you'll have to write at least one sorted file to a temporary file.

diff - file.txt

will diff stdin versus a file.txt. The '-' represents stdin

EDIT: I'd assumed that the process substitution would work via stdin. But that's not the case and the above is going via /dev/fd/{num} as pointed out by VardhanDotNet above.

Solution 6 - Unix

In fish shell,

diff (sort a.txt | psub) (sort b.txt | psub)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmmccooView Question on Stackoverflow
Solution 1 - UnixDavid SchmittView Answer on Stackoverflow
Solution 2 - UnixhajamieView Answer on Stackoverflow
Solution 3 - UnixIvan BalashovView Answer on Stackoverflow
Solution 4 - UnixMatthieu BROUILLARDView Answer on Stackoverflow
Solution 5 - UnixBrian AgnewView Answer on Stackoverflow
Solution 6 - UnixmhansenView Answer on Stackoverflow