Centos – How to list packages with files in a particular directory

centospackage-managementrpmyum

I'm switching to CentOS from another distribution, and I'm not used to working with yum. I'd like to know if there's a way to know which installed packages have files in a directory.

For example I'd like to know which packages have files within /usr/share/applications.

Looking at what yum provides I saw there's a way to see installed packages (list installed) but even providing -q doesn't get me just the names of the packages. I saw no option to list contents of a single package however.

Is it possible? How could I do it?

Best Answer

There isn't a way to do this using yum but you can craft a rpm command that will do mostly what you want. You'll have to utilize the --queryformat option and iterate through the array of filenames using the little known option [..] in the --queryformat.

NOTE: All these features are discussed in the manual for RPM, Maximum RPM: Taking the Red Hat Package Manager to the Limit.

$ rpm -qa --queryformat '[%{NAME}: %{FILENAMES}\n]' | \
    sed 's#\(/.*/\).*$#\1#' | sort -u | grep '/usr/sbin' | head -10
abrt-addon-ccpp: /usr/sbin/
abrt-addon-pstoreoops: /usr/sbin/
abrt-addon-vmcore: /usr/sbin/
abrt-dbus: /usr/sbin/
abrt: /usr/sbin/
alsa-utils: /usr/sbin/
aoetools: /usr/sbin/
at: /usr/sbin/
authconfig: /usr/sbin/
avahi-autoipd: /usr/sbin/
...

Details

The above --queryformat iterates over the array macro %{FILENAMES} via the [...] notation, printing the name (%{NAME}) of the package they're contained in, along with their full installed path.

Example
$ rpm -q --queryformat '[%{NAME}: %{FILENAMES}\n]' fatrace
fatrace: /usr/sbin/fatrace
fatrace: /usr/sbin/power-usage-report
fatrace: /usr/share/doc/fatrace-0.5
fatrace: /usr/share/doc/fatrace-0.5/COPYING
fatrace: /usr/share/doc/fatrace-0.5/NEWS
fatrace: /usr/share/man/man1/fatrace.1.gz

With this type of output we simply need to chop off the trailing filenames from the above paths. For this I used sed. I then run the output through sort -u to condense any duplicate lines since often times, many packages will install a multitude of files into a single directory. Finally I use grep ... to find the packages which have files in a given directory. To facilitate this further you could do this:

grep $(pwd)
Example
$ pwd
/usr/sbin

$ rpm -qa --queryformat '[%{NAME}: %{FILENAMES}\n]' | \
    sed 's#\(/.*/\).*$#\1#' | sort -u | grep $(pwd)

A list of just package names

To get just the names of the packages in a unique list you can do the following:

$ rpm -qa --queryformat '[%{NAME}: %{FILENAMES}\n]' | \
    sed 's#\(/.*/\).*$#\1#' | sort -u | grep $(pwd) | \
    awk -F: '{print $1}' | head -10
abrt-addon-ccpp
abrt-addon-pstoreoops
abrt-addon-vmcore
abrt-dbus
abrt
alsa-utils
aoetools
at
authconfig
avahi-autoipd

References

Related Question