How to locate directories that contain one or multiple files with particular content

Use find and grep commands to search for directories that contain one or multiple files with particular content.

I have described three different cases that can be used to locate particular directories: based on single file, multiple files or extended single file operations.

Search for mounted devices using specific option

I will inspect mounted filesystem options to display to display those mounted in read-write mode.

Locate options file that contain rw line, print directory name.

$ find /proc/fs/ -type f -name options -exec grep -l ^rw$ {} \; | xargs dirname
/proc/fs/ext4/dm-1
/proc/fs/ext4/sda2

Strip leading directory components to display only directory name.

$ find /proc/fs/ -type f -name options -exec grep -l ^rw$ {} \; | xargs dirname | xargs basename -a

or

$ find /proc/fs/ -type f -name options -exec grep -l ^rw$ {} \; | xargs dirname | awk --field-separator '/' '{print $NF}'
dm-1
sda2

Search for path describing particular USB device

I will inspect idVendor and idProduct files to find path for Realtek 0bda:5682 device.

$ find -L /sys/bus/usb/devices/ -maxdepth 2 -type f -name idVendor -exec grep -l "0bda" {} \; | \
    while read line; do \
      location=$(dirname $line); \
      grep -q "5682" $location/idProduct;
      if [ "$?" -eq "0" ]; then \
        echo $location;
      fi
    done
/sys/bus/usb/devices/2-5

Search for CPUs running at high speed

I will inspect current CPUs frequency and display those running at high speed (> 2 GHz).

$ find /sys/devices/system/cpu -maxdepth 3 -type f -name cpuinfo_cur_freq | \
    while read file; do \
      content=$(sudo cat $file); \
      freq=$(expr $content / 1000); \
      if [ "$freq" -gt "2000" ]; then \
        echo $file | \
          xargs dirname | xargs basename -a | \
          sed s/policy/cpu/; \
      fi \
    done
cpu3
cpu1

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system. He is also open for new opportunities and challenges.