DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk12 min

How to Use grep Regular Expressions to Search for Text in Linux

A practical, detailed guide to searching Linux text with grep regular expressions, covering matcher modes, shell quoting, regex syntax, precision options, pattern files, recursive searches, binary data, locale, and troubleshooting.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

grep searches text one line at a time and prints the lines that match a pattern. For ordinary searches, run grep 'pattern' file; for alternation, grouping, and readable intervals, use extended regular expressions with grep -E. Quote the pattern so your shell passes characters such as |, $, and * to grep unchanged.

This guide explains the four grep matcher families, the regular-expression syntax that matters in daily Linux work, precise matching with words and whole lines, multiple patterns, recursive and piped searches, locale and binary-data caveats, and the failure modes that make an apparently correct command return the wrong result.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What grep searches and what it prints

GNU grep searches named input files, or standard input when no file is named, for lines containing a match to the pattern. A match can be a literal string or a regular expression, depending on the matcher you choose. By default, matching lines are written to standard output; the original files are not changed.

The basic form is:

grep [options] 'pattern' file...

For example:

grep 'timeout' server.log

That command prints every line in server.log containing the six-letter sequence timeout. It does not require the word to stand alone, so it can also match timeout_ms or connection_timeout. Regular expressions let you describe a shape rather than one fixed string.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

If you omit the file name, grep reads standard input. This makes it useful in pipelines:

journalctl -b | grep -i 'failed'

A single hyphen can also explicitly name standard input:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cat server.log | grep 'timeout' -

Using a pipeline is convenient, although invoking grep with the file directly is usually simpler and avoids an unnecessary process.

Choose the grep matcher before writing the pattern

GNU grep provides four matcher families. The same characters can have different meanings in each family, so select the family that fits the job before debugging the expression.

Matcher Option What it does Best use Portability note
Basic regular expressions -G, the default Traditional POSIX BRE syntax Simple expressions and scripts that already use BRE Grouping, alternation, and intervals commonly need backslashes
Extended regular expressions -E ERE syntax with clearer grouping, alternation, and intervals Most new regex searches that need more than literals and classes Widely available in GNU and POSIX-style grep implementations
Fixed strings -F Treats the pattern as literal text, not a regex Exact text searches, especially when metacharacters should be ordinary characters Usually the most predictable and often faster for literal searches
Perl-compatible regular expressions -P Enables PCRE syntax in GNU grep builds that support it Features unavailable in POSIX BRE or ERE Availability, warnings, and behavior vary by build; portability is lower

The default is BRE, so these two commands are not equivalent:

grep 'error|failed' app.log
grep -E 'error|failed' app.log

In the first command, the vertical bar is generally literal in BRE. In the second, it means alternation and matches either error or failed. Prefer -E when grouping and alternation make the intended pattern clearer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quote the pattern so the shell does not rewrite it

Shells interpret characters before grep receives them. Single quotes are the safest default for a fixed pattern:

grep -E '^(ERROR|WARN):' app.log

Without quotes, a shell can expand asterisks, interpret dollar signs, split on spaces, or treat parentheses and other characters specially. Double quotes prevent pathname expansion but still allow variable expansion and command substitution. Use double quotes intentionally when a shell variable must be inserted:

needle='connection refused'
grep -F "$needle" app.log

Do not use eval to assemble grep commands. If user input becomes a pattern, decide whether it should be literal or a regex and pass it as one argument. For a pattern that starts with a hyphen, use -e or the end-of-options marker:

grep -e '-pattern' file.txt
grep -- '-pattern' file.txt

The -e form is especially useful when a pattern comes from a variable or another command and might begin with -.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Regular-expression building blocks

Literal characters

Letters and digits normally match themselves. A pattern such as 404 finds those characters anywhere in a line. To search for punctuation that has regex meaning, either escape it or use fixed-string mode:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
grep -F 'price $5.00' receipt.txt
grep 'price $5.00' receipt.txt

Fixed-string mode is easier to read when no pattern behavior is required.

Anchors for line boundaries

^ anchors a match at the beginning of a line, and $ anchors it at the end. This distinguishes a prefix or suffix from text appearing in the middle:

grep '^ERROR' app.log
grep 'completed$' app.log

To match a line that consists only of one value, anchor both sides:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
grep '^READY$' status.txt

The terminating newline is not part of the line matched by a POSIX regular expression, so $ refers to the visible end of the line.

The dot and repetition

A dot (.) matches one character. It is broad: v.1 can match vA1, v-1, or v.1. Escape the dot when you need a literal period.

Repetition operators describe how many times the preceding atom may occur. In ERE, the common forms are:

  • *: zero or more occurrences.
  • +: one or more occurrences.
  • ?: zero or one occurrence.
  • {m}: exactly m occurrences.
  • {m,n}: from m through n occurrences.

For example, this ERE finds a three-digit code:

grep -E '^[0-9]{3}$' codes.txt

In BRE, interval expressions are commonly written with escaped braces, as in ^[0-9]{3}$. ERE is usually easier to read when a pattern contains several quantifiers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Bracket expressions and character classes

A bracket expression matches one character from a set:

grep -E 'file[0-9].log' names.txt

This accepts file0.log through file9.log. A range such as [a-z] depends on the current locale, so it may not represent exactly the ASCII ordering you expect. POSIX character classes are clearer when portability across locales matters:

  • [[:digit:]] for digits.
  • [[:lower:]] for lowercase letters according to the locale.
  • [[:upper:]] for uppercase letters according to the locale.
  • [[:space:]] for whitespace characters.
  • [[:alnum:]] for letters and digits.

Use the class inside an outer bracket expression, as in [[:digit:]], not as a bare word. To negate a bracket expression, put ^ immediately after the opening bracket:

grep -E '[^[:space:]]' file.txt

That expression finds a line containing at least one non-whitespace character.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Grouping and alternation

ERE makes grouping and alternation explicit:

grep -E '^(ERROR|WARN):' app.log

The parentheses group the alternatives, and | means either alternative. In BRE, grouping is commonly written (ERROR|WARN) with GNU extensions for alternation, which is harder to scan. If a pattern has alternatives, choose -E unless you have a specific reason to preserve BRE syntax.

Useful search recipes

Find either of several words

Use ERE alternation and quote the expression:

grep -E 'timeout|connection refused' server.log

This matches a line containing either phrase. Parentheses help when an alternative is part of a larger expression:

grep -E '^(ERROR|WARN):' app.log

Ignore case while matching a whole word

The -i option makes matching case-insensitive. The -w option asks grep to match a whole word rather than a substring:

grep -iw 'warning' app.log

This can match Warning and WARNING, but avoids matching a longer word such as warning_count when grep’s word-boundary rules do not consider the underscore a separator. If your definition of a boundary is more specific, use explicit anchors or bracket expressions instead of assuming -w models every language’s word syntax.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Match an entire line

Use -x when the complete line must equal the pattern:

grep -x 'READY' status.txt

This is less error-prone than adding anchors when the pattern is meant to be a literal value. For a regular expression that must cover the whole line, anchors remain useful, for example grep -xE '[0-9]{4}' years.txt.

Show lines that do not match

-v inverts selection. To remove blank lines and comments from a simple configuration file:

grep -v '^#' config.conf

That command removes lines beginning with #, but it keeps blank lines. To exclude both blank lines and comments, use an ERE that matches either case and invert it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
grep -vE '^(#|$)' config.conf

Match a structured prefix

Anchors and classes can validate a line’s basic shape. For a line beginning with an uppercase severity followed by a colon:

grep -E '^(ERROR|WARN|INFO):' app.log

This does not validate the rest of the line; grep reports the complete line whenever the prefix matches. Regular expressions in grep select lines, not isolated records or fields.

Search with several patterns

Repeat -e to provide multiple patterns. A line is selected if it matches at least one of them:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
grep -e 'timeout' -e 'connection refused' server.log

This form avoids embedding complex alternation and handles patterns that begin with a hyphen. It also lets a script build arguments without changing the meaning of each pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a larger or reusable list, put one pattern per line in a file and use -f:

grep -f patterns.txt access.log

Each nonempty line in patterns.txt is interpreted according to the selected matcher. With the default BRE mode, patterns in the file are BREs; add -E if they are EREs:

grep -E -f patterns.txt access.log

When the list is intended to contain literal search terms, use fixed-string mode:

grep -F -f literal-terms.txt access.log

Keep the file’s syntax consistent. A term containing regex punctuation can produce surprising matches unless -F is used or the punctuation is escaped.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Control output for investigation and scripts

Grep’s default output is the complete matching line. Several options make that output easier to use:

  • -n prefixes each result with its line number.
  • -H prints the file name, useful when one file would otherwise be ambiguous.
  • -h suppresses file names when searching multiple files.
  • -c prints a count of matching lines per file.
  • -l prints only names of files with at least one match.
  • -L prints only names of files with no match.
  • -o prints only the matching portion rather than the complete line; support and details can differ among implementations.

For example, to locate and number error lines in several logs:

grep -nH -E '^(ERROR|FATAL):' *.log

To count files containing a whole-word warning:

grep -ilw 'warning' logs/*.log

These options affect presentation, not the underlying regular-expression rules.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Search directories and standard input deliberately

When the input is a directory tree, recursive options let grep visit files below a starting directory. GNU grep’s -r follows ordinary directory traversal rules, while -R also follows symbolic links encountered during traversal. Use recursion with a deliberate starting point and a restrictive pattern:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
grep -RInE '^(ERROR|WARN):' /var/log

Here -I asks grep to skip binary files, -n adds line numbers, and -E enables the grouped alternatives. Recursion can include generated files, caches, and very large trees, so restrict the path or file set when practical. If you need filename filtering, combine grep with a file-selection command rather than assuming every file under the directory is text.

For standard input, remember that grep receives the output exactly as the previous command emits it. A command that formats, colors, or truncates its output can change what the regex sees:

printf '%sn' 'ERROR: disk full' 'INFO: retry' | grep -E '^ERROR:'

Use printf rather than an unquoted echo when constructing test input, because echo behavior varies for backslashes and options.

BRE, ERE, fixed strings, and PCRE in practice

Goal Recommended command Why
Find an exact phrase containing punctuation grep -F 'price $5.00' receipt.txt Regex metacharacters remain literal
Find one of several alternatives grep -E 'timeout|failed' app.log Readable ERE alternation
Preserve an existing basic regex grep -G 'pattern' file Explicitly selects the default BRE family
Use a feature specific to Perl-compatible syntax grep -P 'pattern' file Only when the installed GNU grep supports PCRE and portability is acceptable

Do not select -P merely because a pattern looks complicated. PCRE support is not guaranteed by every grep implementation, and GNU grep may issue warnings or behave differently across builds. If BRE or ERE can express the requirement, they are generally safer choices for scripts intended to run on multiple Linux environments.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Locale, encoding, and binary-data caveats

Locale settings influence ranges and POSIX character classes. A range such as [a-z] is interpreted according to the active locale, while a POSIX class such as [[:lower:]] describes lowercase characters according to that same locale. If a script requires byte-oriented ASCII behavior, set and document the locale deliberately, commonly with an environment such as LC_ALL=C for that command:

LC_ALL=C grep -E '^[A-Z]+$' identifiers.txt

Changing the locale changes what counts as a character class member, so do it only when that is the intended behavior.

GNU grep can classify input containing null bytes or encoding errors as binary. In binary mode it may suppress normal matching details and report that a binary file matches instead. This is a safety signal, not proof that the file has no useful text. If you know the input should be treated as text, GNU grep provides text-handling options such as -a; use them carefully because binary data can contain control characters that make terminal output unsafe or unreadable. The -I option is useful during broad recursive searches when binary files should be skipped.

Understand grep’s exit status in scripts

Grep communicates more than output. Its exit status is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • 0 when at least one line matched.
  • 1 when no line matched.
  • 2 when an error occurred, such as an unreadable file or invalid pattern.

That distinction matters in shell scripts. A no-match result is often an expected condition, not a command failure:

if grep -qE '^READY$' status.txt; then
printf '%sn' 'ready'
else
printf '%sn' 'not ready or unreadable' >&2
fi

The -q option suppresses normal output and lets the status carry the result. If you need to distinguish no match from an I/O or syntax error, inspect the status explicitly rather than treating every nonzero value as identical.

A practical troubleshooting sequence

The command matches too much

  • Replace a loose substring with -w, -x, or explicit ^ and $ anchors.
  • Escape dots and other metacharacters that should be literal, or switch to -F.
  • Check whether a bracket expression or .* is broader than intended.

The command matches nothing

  • Check the matcher family. An alternation written for ERE may be literal in BRE.
  • Inspect shell quoting. An unquoted $, *, or backslash may have been consumed before grep ran.
  • Use grep -n or cat -vet to reveal line endings, tabs, and trailing spaces.
  • Try a literal probe with grep -F to confirm that the expected text is present.
  • Check case with -i and check whether the input is being read from the file or from a transformed pipeline.

Grouping or intervals behave unexpectedly

Confirm whether the pattern is BRE or ERE. In ERE, write (...), |, and {m,n}. In BRE, grouping and intervals commonly require backslashes. If readability matters more than preserving an old command, rewrite it with grep -E and single quotes.

A pattern beginning with a hyphen is treated as an option

Pass it with -e or use -- before the pattern. This is especially important when the pattern is supplied by a user or read from a variable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Output says a binary file matches

The input contains bytes grep considers binary, often null characters or encoding problems. Decide whether to skip it with -I, inspect it with a binary-aware tool, or deliberately force text mode with GNU grep’s -a. Do not blindly force text mode on unknown files.

A compact decision guide

  1. Decide whether the search term is literal. If yes, start with grep -F.
  2. If it is a regex, choose ERE with -E when you need grouping, alternation, or readable intervals; use the default BRE only when its syntax is intentional.
  3. Quote a fixed pattern with single quotes. Use double quotes only when variable expansion is required.
  4. Add precision: -i for case-insensitive matching, -w for a whole word, -x for a whole line, and anchors for exact positions.
  5. Use repeated -e options for a short list or -f for a maintained pattern file.
  6. Choose output options such as -n, -l, -c, or -o only after deciding what the next command or reader needs.
  7. For scripts, handle exit statuses 0, 1, and 2 separately when a missing match is not an error.
  8. For portable automation, prefer POSIX BRE or ERE and POSIX character classes; reserve -P for environments where PCRE support is known.

A reliable starting pattern for many log searches is therefore:

grep -nH -iE '^(error|warn|failed):' app.log

It reads one file, uses ERE grouping and alternation, ignores case, anchors the severity at the beginning of the line, and reports both line numbers and the file name. From there, narrow the expression or change the matcher only when the data and portability requirements justify it.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.