Grep

The grep command-line utility is used for searching plain-text data sets for lines that match a regular expression. It is generally used in collaboration with other Linux commands, such as ls, cat, etc., to provide powerful search functionality in files, consoles, IO streams, etc.

Options

OptionsValuesDescription
-iNACase-insensitive search
-A <LINE_NO>NADisplay LINE_NO lines after the match
-B <LINE_NO>NADisplay LINE_NO lines before the match
-C <LINE_NO>NADisplay LINE_NO lines both before and after the match(around)
-rNARecursive search across all nested files and folders
-vNAInvert the search results
-cNACount the number of search results
-lNADisplay only the file names which have the searched results
-oNAShow only searched results, NOT the whole line
-e “REGEX_PATTERN”NASpecify the regex pattern to be searched
-nNALine number for the search results

Packages and Install

OSPackage Install CMD
Debian/ubuntuapt install grep
Centos/fedora(dnf, microdnf, rpm, yum)yum install grep
Arch (pacman)pacman -S grep
Alpine (apk-docker)apk –no-cache add grep

Examples

For Detailed Regex related docs, please refer regex

  • Search a match string in a file
grep "test" test_file.txt
  • Recursively search all the files and in the sub-directory
grep -r "test" /some/tmp/dir/*
  • Get the lines that do not start with a vowel, along with line numbers
grep -v -n -e "^[aeiouAEIOU].*" test_file.txt
  • Case-insensitive search with 2 lines above and below to display in all the files in the current working directory.
grep -i -A 2 -B 2 "test" *
  • Get all the details for the wired ethernet network interface
ifconfig | grep -A 4 ens*
  • Get all the Java processes running.
ps aux | grep java