Tools: Mastering Grep command in Linux/Unix: A Beginner's Tutorial (2026)
Source: DigitalOcean
By Anish Singh Walia, Pankaj Kumar and Manikandan Kurup Grep, short for “global regular expression print”, is a command used for searching and matching text patterns in files using regular expressions. Furthermore, the command comes pre-installed in every Linux distribution. In this guide, we will look at the most common grep command use-cases. Grep command can be used to find or search a regular expression or a string in a text file. To demonstrate this, let’s create a text file welcome.txt and add some content as shown. Great! Now we are ready to perform a few grep commands and manipulate the output to get the desired results. To search for a string in a file, run the command below. As you can see, grep has not only searched and matched the string “Linux” but has also printed the lines in which the string appears. If the file is located in a different file path, be sure to specify the file path as shown below: If you are working on a system that doesn’t display the search string or pattern in a different color from the rest of the text, use the --color option to make your results stand out. If you wish to search for a string in your current directory and all other subdirectories, search using the -r flag as shown: In the above example, our search results gave us what we wanted because the string “Linux” was specified in uppercase and also exists in the file in uppercase. Now let’s try and search for the string in lowercase. Nothing from the output, right? This is because grep could not find and match the string “linux” since the first letter is lowercase. To ignore case sensitivity, use the -i flag and execute the command below: Awesome, isn’t it? The -i flag is normally used to display strings regardless of their case sensitivity. To count the total number of lines where the string pattern appears or resides, execute the command below: To invert the grep output, use the -v flag. The -v option instructs grep to print all lines that do not contain or match the expression. This means that instead of printing matching lines, grep does the opposite and prints all of the lines that don’t match the expression. Going back to our file, let us display the line numbers as shown. Hit ESC in the Vim editor, type a colon followed by: Now, to display the lines that don’t contain the string “Linux”, run: As you can see, grep has displayed the lines that do not contain the search pattern. To number the lines where the string pattern is matched, use the -n option as shown: Passing the -w flag will search for the line containing the exact matching word as shown: No results will be returned because we are not searching for a pattern but an exact word! The grep command can be used together with pipes for getting distinct output. For example, if you want to know if a certain package is installed in an Ubuntu system, execute: For example, to find out if OpenSSH has been installed in your system, pipe the dpkg -l command to grep as shown: You can use the -A or -B flags to display the number of lines that either precede or come after the search string. The -A flag denotes the lines that come after the search string and -B prints the output that appears before the search string. For example: This command displays the line containing the string plus 4 lines of text after the ens3 string in the ifconfig command. Conversely, in the example below, the use of the -B flag will display the line containing the search string plus 4 lines of text before the ether string in the ifconfig command. The term REGEX is an acronym for REGular EXpression. A REGEX is a sequence of characters that is used to match a pattern. Below are a few examples: To print lines beginning with a certain character, the syntax is: For instance, to display the lines that begin with the letter “d” in our welcome.txt file, we would execute: To display lines that end with the letter ‘x’, run: If you need to learn more about grep command usage, run the command below to get a sneak preview of other flags or options that you may use together with the command. We appreciate your time for going through this tutorial. Feel free to try out the commands and let us know how it went. The grep command supports Extended Regular Expressions (ERE) using the -E flag, also known as egrep. To search with groups and back-references, use: For a deep dive into regex patterns, check out this tutorial on Using Grep Regular Expressions to Search for Text Patterns in Linux. The GNU grep implementation optimizes searches using multi-threading. If available, grep internally uses AVX2 vectorization to speed up pattern matching. For multi-threaded searching on large files, you can use: Or leverage parallel execution with xargs: This allows grep to process multiple files in parallel, improving performance on multi-core systems. When using grep -r, be mindful of: Symbolic Links Loops: Use grep -R to follow symbolic links safely. Binary File Output: Use grep --binary-files=text to process binaries as text. Permission Errors: Run grep with sudo for restricted directories. Example of a safer recursive search: The grep (Global Regular Expression Print) command is a powerful text-searching utility in Linux/Unix that allows users to search for specific patterns in files or output streams. It supports basic and extended regular expressions to match complex text patterns efficiently. For a more developer-friendly alternative, you can check out How to Install and Use Ack: A Grep Replacement for Developers on Ubuntu and Awk command in Linux. To search for a word or phrase in a file, use: For recursive searching in directories, use: To enhance searching with regular expressions, refer to Using Grep Regular Expressions to Search for Text Patterns in Linux. Basic usage includes: To ignore case sensitivity: For advanced examples, you can check out this tutorial on Top 50+ Linux Commands You MUST Know. To search for a pattern in all files within a directory: To include hidden files: Be cautious with recursive searches, as large directories can slow down the process. To search for a pattern across multiple files in subdirectories, use the -r flag: For better control, use the --include or --exclude options: One common pitfall with recursive searches is encountering symbolic links, which can be handled using the -R option instead of -r. grep is mainly used for searching patterns in text, whereas awk is more powerful for text processing and can manipulate data based on conditions. grep supports regex for advanced searching: For a detailed guide, refer to our tutorial on using Grep Regular Expressions to Search for Text Patterns in Linux. Yes! grep is widely used in shell scripts for filtering output. For more automation tips, check out this tutorial on Top 50 Linux commands. The grep command is an essential tool for searching text patterns in Linux and Unix systems. Whether you are filtering log files, searching for specific words in code repositories, or processing large datasets, grep provides powerful options like regular expressions, recursive searching, and multi-threaded execution to make your searches more efficient. It is a must-have tool for system administrators, developers, and DevOps engineers. Keep experimenting with different flags and combinations to unlock its full potential. Check out these related tutorials: Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about our products I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers. Hi Your tutorials are helpful and well explained, do you perhaps have linux video tutorials Please complete your information! Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation. Full documentation for every DigitalOcean product. The Wave has everything you need to know about building a business, from raising funding to marketing your product. Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter. New accounts only. By submitting your email you agree to our Privacy Policy Scale up as you grow — whether you're running one virtual machine or ten thousand. From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.