How to list packages available (and installed) from a specific repository

I don't know of a simple APT command that could give the answer to the question of this post, thus I made a little awk script to filter the output of apt-cache policy to get what I want.

The apt-cache policy package command gives an output like this:
firefox:
  Installed: 3.6.17+build3+nobinonly-0ubuntu0.10.10.1
  Candidate: 3.6.17+build3+nobinonly-0ubuntu0.10.10.1
  Version table:
*** 3.6.17+build3+nobinonly-0ubuntu0.10.10.1 0
        500 http://archive.ubuntu.com/ubuntu/ maverick-updates/main i386 Packages
        500 http://security.ubuntu.com/ubuntu/ maverick-security/main i386 Packages
        100 /var/lib/dpkg/status
     3.6.10+build1+nobinonly-0ubuntu3 0
        500 http://archive.ubuntu.com/ubuntu/ maverick/main i386 Packages

It contains all repositories that the given package is available from. You can run apt-cache policy for all packages in the APT cache by supplying the proper .* regular expression. With a little scripting (I chose awk for this) you can filter only for the package entries that contain a specific string (or regular expression).

Eg. to filter for packages that are found in the http://ppa.launchpad.net/freenx-team/ppa/ubuntu FreeNX repository and are already installed, you can use the following:
apt-cache policy '.*' | awk '
/^[a-zA-Z0-9]+/ {
  if (m != "") print str
  str = $0
  m = ""
  next
}
{
  str = str "\n" $0
  if (match($0, "^[ \t]*\\*\\*\\*")) {
    getline;
    str = str "\n" $0
    if (index($0, "http://ppa.launchpad.net/freenx-team/ppa/ubuntu")) m = 1
  }
}
END {
  if (m != "") print str
}'

For easier copy&paste you can merge it into a one-liner:
apt-cache policy '.*' | awk '/^[a-zA-Z0-9]+/ { if (m != "") print str; str = $0; m = ""; next } { str = str "\n" $0; if (match($0, "^[ \t]*\\*\\*\\*")) { getline; str = str "\n" $0; if (index($0, "http://ppa.launchpad.net/freenx-team/ppa/ubuntu")) m = 1 } } END { if (m != "") print str }'

Since some versions of apt-cache do not recognize regular expressions in the package list (eg. the one in Debian Lenny: apt-cache v0.7.20.2), you can use the following workaround:
apt-cache pkgnames | sort | xargs apt-cache policy | awk '/^[a-zA-Z0-9]+/ { if (m != "") print str; str = $0; m = ""; next } { str = str "\n" $0; if (match($0, "^[ \t]*\\*\\*\\*")) { getline; str = str "\n" $0; if (index($0, "http://ppa.launchpad.net/freenx-team/ppa/ubuntu")) m = 1 } } END { if (m != "") print str }'

To get all (not just the installed) packages available from a repo, leave out the *** matching stuff. Like this:
apt-cache pkgnames | sort | xargs apt-cache policy | awk '/^[a-zA-Z0-9]+/ {if (m != "") print str; str = $0; m = ""; next} {if (index($0, "http://ppa.launchpad.net/freenx-team/ppa/ubuntu")) m = 1; str = str "\n" $0} END {if (m != "") print str}'

Hope this helps for people without (awk) scripting knowledge (and/or interest/time to write the script).