Search (Bash)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

How to find stuff on a computer using Bash?

Find a textstring

To find a text string within the files that are located in the PWD:

grep -rn . -e "my-search-string"

E.g.:


grep -rn . -e Sofia

grep -rn . -e "Sofia" # same result
  • grep: The command-line tool used for searching text within files
  • -r: Recursively search through directories, meaning it will look inside all subdirectories from the current location
  • -n: Show line numbers in the output, making it easier to locate occurrences of the search string
  • .: Specifies the starting directory (the current directory). This tells grep to search in all files under the current directory - This is what designates the files in the PWD as input for grep
  • -e "my-search-string": The search pattern ("my-search-string") that grep looks for. The -e flag explicitly defines the search pattern. It's needed, also when using just one pattern.

This only works for files that are readible by grep. So, text files are fine, but Witer- or Calc files probably not.

I find it difficult to memorize this specific application of grep. I can't add it as an alias to .bashrc, as aliases don't take arguments, but I could define in in .bashrc as a function. E.g.:

mysearchalias
{
   grep -rn . -e "$1"
}

Find files - locate

locate is probably the simplest and most limited way to find files. For example, you can't search in a specific tree, only globally (I think).

Find directories & files - find

Use find to search for directory names and/or file names. By default, find works recursively. E.g.:

# All directories
########################################
#
find ~/Dropbox/Music_Dropbox -type d


# All files
########################################
#
find ~/Dropbox/Music_Dropbox -type d


# Directories with a specific name
########################################
#
find ~/Dropbox/Music_Dropbox -type d -name "Radio*"


# Files with a specific name
########################################
#
find ~/Dropbox/Music_Dropbox -type f -name "*.mp4"

See Find (Linux) for more.

Locate executables

Use which to locate the executable that is active for a given command. It searches for the command in the directories listed in the PATH environment variable and returns the full path of the executable.

E.g.:

$ which wp
/opt/wp

Locate executables, aliases & functions

use type to find all kinds of executables. E.g.:

$ type ll
ll is aliased to `ls -alF'

This should also work for functions, but so far I haven't figured out how to do so. E.g., none of these work:

type prologue
type prologue()
type set_variables
type set_variables()
type assign_site_array
type assign_site_array()

See also