Skip to main content

find, search, grep

find

use cases:

  • find ./subfolder -name sample.txt - Search a file with specific name
  • find ./subfolder -name *.txt - Search a file with pattern
  • find ./GFG -name sample.txt -exec rm -i {} \; - find and delete a file with confirmation
  • find ./subfolder -empty - Search for empty files and directories
  • find ./subfolder -perm 664 - Search for file with entered permissions
  • find ./ -type f -name "*.txt" -exec grep 'some Phrase' {} \; - Search text within multiple files

more examples

find /path -name *.txt
find /path -type f -name test.txt
find /path -name failed*.* -type f
find /path -type f -not -name "*.html"
find / -name "file.txt" -size +4M
find /dev/ -type b -name "sda*"
find ./*file*

grep

grep [OPTION]... PATTERNS [FILE]...

  • options
    • -B <numb> - show numb lines before match
    • -A <numb> - show numb lines after match
    • -i - ignore case distinctions in patterns and data
    • -r, --recursive - like --directories=recurse
    • -v, --invert-match - To display only the lines that do not match a search pattern
    • --exclude-dir=<foldername> - exclude folder from search
    • -n, --line-number - Prefix each line of output with the 1-based line number within its input file.

examples

  • grep -ir --exclude-dir=vendor skeleton . - find all occurences of "skeleton" in the current working dir
  • grep -i "some string" path/**/files.log - search string in log files

sed

sed -i 's/SEARCH_REGEX/REPLACEMENT/g' INPUTFILE

  • -i - By default, sed writes its output to the standard output. This option tells sed to edit files in place. If an extension is supplied (ex -i.bak), a backup of the original file is created.
  • s - The substitute command, probably the most used command in sed.
  • `/ / /`` - Delimiter character. It can be any character but usually the slash (/) character is used.
  • SEARCH_REGEX - Normal string or a regular expression to search for.
  • REPLACEMENT - The replacement string.
  • g - Global replacement flag. By default, sed reads the file line by line and changes only the first occurrence of the SEARCH_REGEX on a line. When the replacement flag is provided, all occurrences are replaced.
  • INPUTFILE - The name of the file on which you want to run the command.