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
Options | Values | Description |
---|---|---|
-i | NA | Case-insensitive search |
-A <LINE_NO> | NA | Display LINE_NO lines after the match |
-B <LINE_NO> | NA | Display LINE_NO lines before the match |
-C <LINE_NO> | NA | Display LINE_NO lines both before and after the match(around) |
-r | NA | Recursive search across all nested files and folders |
-v | NA | Invert the search results |
-c | NA | Count the number of search results |
-l | NA | Display only the file names which have the searched results |
-o | NA | Show only searched results, NOT the whole line |
-e “REGEX_PATTERN” | NA | Specify the regex pattern to be searched |
-n | NA | Line number for the search results |
Packages and Install
OS | Package Install CMD |
---|---|
Debian/ubuntu | apt 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