Get name and version of available packages to text file - name and version only on same line, per package

If you have a list of packages (say, in a file named input, one per line), then you can do:

while read package
do
    echo $package "$(apt-cache show $package | awk '/Version/{print $2}')"
done < input > Output.txt

After some wrangling with the aptitude documentation, including this Debian aptitude search term reference, I managed to come up with this ugly one-liner

aptitude -F '%p %V' --group-by=none --sort=name,~version versions \
  ?exact-name\({python-numpy,mysql-server,python-six,python-wheel,apache2,python-urllib3,python-setuptools}\) \
  | sort -uk1,1
  • -F '%p %V' formats the output as package name and then candidate version
  • --sort=name,~version sorts by package name and version descending so that we can use sort -u to skim off the newest
  • ?exact-name() prevents the search from being expanded to include things like mysql-server-5.5 for mysql-server

Note the ugly brace expansion for the list of packages to check: there doesn't seem to be an option like -oAptitude::Some::Param=true to enforce ?exact-name() globally.


FWIW the apt-show-versions utility seems to get 90% of the way there with 10% of the effort: here are the results for the packages you mention on my 14.04.3 system:

$ aptitude -F '%p %V' --group-by=none --sort=name,~version versions \
  ?exact-name\({python-numpy,mysql-server,python-six,python-wheel,apache2,python-urllib3,python-setuptools}\) \
  | sort -uk1,1
apache2 2.4.7-1ubuntu4.8                                                        
mysql-server 5.5.46-0ubuntu0.14.04.2                                            
python-numpy 1:1.8.2-0ubuntu0.1                                                 
python-setuptools 3.3-1ubuntu2                                                  
python-six 1.5.2-1ubuntu1                                                       
python-urllib3 1.7.1-1ubuntu4                                                   
python-wheel 0.24.0-1~ubuntu1                                                   

whereas

$ apt-show-versions python-numpy mysql-server python-six python-wheel apache2 python-urllib3 python-setuptools
apache2 not installed
mysql-server:all/trusty-security 5.5.46-0ubuntu0.14.04.2 uptodate
python-numpy:amd64/trusty-updates 1:1.8.2-0ubuntu0.1 uptodate
python-setuptools:all/trusty-updates 3.3-1ubuntu2 uptodate
python-six:all/trusty-updates 1.5.2-1ubuntu1 uptodate
python-urllib3:all/trusty-updates 1.7.1-1ubuntu4 uptodate
python-wheel:all/trusty-updates 0.24.0-1~ubuntu1 uptodate

The most obvious difference is it apparently doesn't include packages that are not currently installed.