How to match two strings that are present in one line with grep in Linux?

The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display lines that contain the pattern we are searching for. When we need to find lines containing multiple strings, we can combine grep commands or use pattern matching techniques.

The pattern we search for is referred to as a regular expression, and grep provides several methods to match multiple strings on the same line.

Basic Grep Syntax

grep [options] pattern [files]

Common Grep Options

Option Description
-c Lists only a count of matching lines
-h Displays matched lines only (no filenames)
-i Ignores case for matching
-n Displays matched lines with line numbers
-v Prints lines that do NOT match the pattern
-r Searches recursively in subdirectories

Methods to Match Multiple Strings

Consider a sample file sample.txt with the following content −

orange apple is great together
apple not great
is apple good
orange good apple not
banana orange tasty

Method 1 − Using Pipe with Multiple Grep Commands

This method filters the output of the first grep command through the second grep command −

grep 'orange' sample.txt | grep 'apple'
orange apple is great together
orange good apple not

Method 2 − Using Regular Expression with AND Logic

Use the .* wildcard to match any characters between the two strings −

grep 'orange.*apple' sample.txt
orange apple is great together
orange good apple not

To match either order of the strings, use alternation −

grep -E 'orange.*apple|apple.*orange' sample.txt

Method 3 − Using Extended Regular Expressions

The -E flag enables extended regular expressions for more complex pattern matching −

grep -E '(orange.*apple|apple.*orange)' sample.txt

Searching in Multiple Files

To search for multiple strings across all files in a directory −

grep -rni 'orange.*apple' *

To search only in the current directory (not subdirectories) −

grep -s 'orange.*apple' *

Case-Insensitive Matching

Use the -i flag to ignore case differences −

grep -i 'orange.*apple' sample.txt

Comparison of Methods

Method Syntax Advantage Limitation
Pipe Method grep 'word1' file | grep 'word2' Simple and readable Processes file twice
Regex Method grep 'word1.*word2' file Single pass through file Order-dependent
Extended Regex grep -E '(word1.*word2|word2.*word1)' file Order-independent More complex syntax

Conclusion

Matching multiple strings on the same line with grep can be accomplished using pipes, regular expressions, or extended regular expressions. The pipe method is simplest for beginners, while regex methods offer better performance for large files. Choose the method that best fits your specific use case and complexity requirements.

Updated on: 2026-03-17T09:01:38+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements