Find

find / -type f -name "filename.txt" 2>/dev/null
  • find: This is the main command for searching files and directories.
  • /path/to/directory: Replace this with the path to the directory where you want to search. You can use / to search from the system root directory.
  • -type f: This specifies that you are searching for files (not directories). (Optional)
  • -name "example.txt": Here you define the name of the file you want to find. Replace "example.txt" with the name of the file you are searching for.
  • /dev/null: Anything written to /dev/null is discarded, effectively "disappearing." It is often referred to as a "black hole" because any data sent there is lost. When you combine 2> with /dev/null, you are instructing the shell to redirect all error messages to /dev/null, where they will be discarded. This is useful in scripts or commands where you don't want error messages to pollute your output or interfere with the execution of other commands (such as "permission denied" when trying to access restricted directories).

Search for text within a file

find /path/to/directory -type f -exec grep -l 'specific_text' {} + 2>/dev/null
  1. /path/to/directory: Replace this with the path to the directory where you want to start the search.
  2. -type f: This instructs find to search only regular files, ignoring directories, symbolic links, etc.
  3. -exec: This is a find argument that allows you to run a command on each file found that matches the search criteria.
  4. grep -l 'specific_text' {}:
  • grep is a tool used to search for text in files.
  • -l (lowercase L) instructs grep to only list the names of the files where the text is found, without displaying the specific line.
  • 'specific_text' is the text you are searching for. Replace this with your text of interest.
  • {} is a placeholder used by find to represent each file found.
  1. +: This ends the -exec command, allowing it to process multiple files at once, which is more efficient than starting a new grep for each file found.

Grep - text within file

Now searches the entire text, not just the file where the text is located.

grep -rnw '/' -e 'searched text' 2>/dev/null
  • The -r option causes the search to be performed recursively in all directories and subdirectories starting from the current directory (/).
  • The -n option causes grep to display the line number for each match found.
  • The -w option causes the search to be for whole words, meaning that "HTB" must be separated by word delimiters, such as spaces or punctuation, to be considered a match.
  • The -e 'HTB' expression specifies the text to be searched.
  • The 2>/dev/null redirection discards error messages, as before, hiding them from the output.