Finding Files and Text with Linux Find and Grep

Jake G January 23, 2020 #Linux #Commandline

Linux has a lot of ways to find files and specific text within files, the most common tools for this are Find and Grep.

Here is a Find command, the first argument is the location to search, type d,f means we are searching directories and files, iname is a case insistive search option that supports regex patterns.

find /media/storage/ -type d,f -iname "*haproxy*"

Here is an example that will search our entire system for a file with the string wireplumber in the filename, while excluding any paths that contain: media, mnt, proc, run.

find / -not \( -path "*/media/*" -prune \) -not \( -path "*/mnt/*" -prune \) -not \( -path "*/proc/*" -prune \) -not \( -path "*/run/*" -prune \) -regex '.*wireplumber.*'

You can also search documents for specific text using grep. The below command searches all txt files in the docs directory for the string haproxy

grep -i --color --binary-files=without-match --include=\*.txt -rnw "/media/docs/" -e "haproxy"

The below can be used to search the entire system, while excluding some directories:

grep -i --color --binary-files=without-match --exclude-dir={sys,proc,run,root,var,etc,boot,tmp,usr,md0,.cache} --include=\*.txt -rnw "/" -e "haproxy"

You can also exclude certain patterns in the filename, use the following to exclude files that contain min as part of the filename:

grep -i --color --binary-files=without-match --include=\* -rnw '/media/docs/' --exclude="*min*" -e "haproxy"

You can also use regular expressions, the below will search for text lines that have both find and chmod:

grep -i --color --binary-files=without-match --include=\*.txt -rnw '/media/docs/' -e ".*find.*chmod.*"