Skip to content

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 lscat, etc., to provide powerful search functionality in files, consoles, IO streams, etc.

Terminal window
# Search a match string in a file
grep "test" test_file.txt
# Search everything
grep "key" *
# 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
OptionsDescription
-iCase-insensitive search
-A 3display 3 lines below the searched result
-B 2display 2 lines above the searched result
-C 4display 4 lines above & below the searched result
-rrecursive search
-vinvert the search result
-ccount the number of searched results
-ldisplay only the filenames
-e “REGEX”regex pattern to search
-nline number of the searched result
-wexact search
-ojust show the matched strings, not the entire line
—colorcolor for search results
Distro/OS/Package ManagerInstall Instruction
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