Mac Terminal iconMac Terminal icon

The command line grep tool is incredibly powerful and useful for searching for matches in files, sorting text and data, finding strings in large files, and so much more. One common situation many command line users may find themselves in, is seeking to grep match for two different strings in a single line.

You can use grep in the Terminal in MacOS for this, or any other unix-based command line prompt, whether that’s Linux, Windows WSL, any version of MacOS / Mac OS X, or even a rooted iOS/iPadOS if you’re into that kind of thing.

Use grep to Match Two Strings on the Same Line

From the command line, try the following syntax to grep match two strings in the same line:
grep "string1" /path/to/file |grep "string2"

For example, this may look like the following:

grep "error" /var/log/messages |grep "critical"

Using grep to Match Two Strings Anywhere in a File or Command Output

Another common situation is to need to use grep to match two different strings contained anywhere in a file or in the output of another command. You can use the -e flag for this purpose, like so:

grep -e String1 -e String2

So for example, for command output, you could use the following command string, in this case matching “CurrentCapacity” and “MaxCapacity”:

ioreg -l| grep -e CurrentCapacity -e MaxCapacity

The command line is intended for advanced users, but grep is a fairly forgiving command and if you’re new to the command line, is a reasonable command to explore and investigate.

And remember, you can also exclude strings from grep if you want to further refine your matching and command output.

If you have another approach to matching two strings in a file or matching multiple strings in command output, share with us in the comments below.

Source