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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

grep reads standard input or named files and prints the lines that contain a match for your pattern. A practical starting point is grep -E 'error|failed' app.log: the shell passes the single-quoted regular expression unchanged, and GNU grep prints every line containing either word. Add anchors, character classes, or options such as -i, -w, and -x when a broad substring search is not precise enough.

This guide explains GNU grep’s regular-expression dialects, reliable shell quoting, pattern construction, multiple-pattern searches, file traversal, and the locale and binary-data cases that can make an apparently correct command behave unexpectedly.

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

What grep actually searches

GNU’s definition is precise: grep searches named input files—or standard input when no file is named, or when a single hyphen-minus is used as a file name—for lines containing a match to the supplied pattern. The match is normally any part of a line; grep then writes the complete matching line, not just the matched characters.

For example:

grep 'timeout' server.log

This searches server.log with grep’s default regular-expression syntax and prints every line containing a sequence that matches timeout. A command can also receive data through a pipe:

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
journalctl -u my-service | grep -i 'failed'

The pattern is interpreted by grep after the shell has processed the command line. That distinction explains why quoting is a core part of writing safe regular-expression commands.

Choose the matching mode before writing the pattern

GNU grep provides four matcher families. Select the simplest one that expresses the search you need.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Mode Option What it interprets When to choose it
Basic regular expressions -G (default) POSIX BRE syntax Simple patterns, or scripts that already use BRE quoting.
Extended regular expressions -E POSIX ERE syntax Grouping, alternation, and repetition are easier to read.
Fixed strings -F Literal text, not regex metacharacters Exact phrases or large lists of literal terms; avoids regex interpretation.
Perl-compatible regular expressions -P PCRE features in GNU grep builds that provide them Only when a PCRE-only feature is required and portability is acceptable.

The default is BRE, so grep 'timeout' file and grep -G 'timeout' file select the same family. ERE is usually the clearest choice when a pattern has alternatives or groups:

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

-P is not a universal portability switch. Support and diagnostics vary between builds, so do not use PCRE syntax merely out of habit. If a BRE or ERE can express the condition, it is generally the more portable option.

Quote patterns so the shell cannot change them

Regular expressions contain characters that also have meaning to a shell, including $, *, parentheses, brackets, and the vertical bar. Single quotes are the safest default because the shell passes every character between them literally:

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

Without quotes, the shell may expand a wildcard, treat a dollar sign as a variable, or interpret other syntax before grep sees it. Use double quotes only when you intentionally need shell expansion, and then escape any regular-expression characters that the shell should not process.

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

A pattern that starts with a hyphen can be mistaken for an option. Give it explicitly with -e, or terminate options with --:

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

The -e form is especially useful in scripts because it unambiguously marks the following argument as a pattern.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Build a regex from anchors, literals, and classes

By default, grep looks for a match anywhere in each input line. Anchors constrain where that match may occur.

Expression Meaning Example use
^ Beginning of the line ^ERROR finds lines whose first characters are ERROR.
$ End of the line ready$ finds lines ending in ready.
. One character (other than the line terminator) v.. finds v followed by two characters.
[0-9] One character from the listed range [0-9][0-9] finds two digits.
[[:digit:]] POSIX digit character class Use when a named class is clearer or locale-aware behavior matters.

To match a complete status line rather than a substring, combine both anchors with -x or write the anchors yourself. These are equivalent for the shown literal:

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

Bracket expressions can list characters, ranges, or POSIX classes. POSIX classes such as [[:lower:]] and [[:digit:]] communicate intent better than ad hoc ranges when a script may run under different locale settings. A range such as [a-z] can be interpreted according to the active locale, so its set is not necessarily identical in every environment.

The dot is deliberately broad: it can match punctuation, digits, and letters. Replace it with a bracket expression when the allowed character set matters. For example, file[0-9] requires one digit after file, whereas file. accepts any single character.

BRE and ERE: the syntax difference that causes most surprises

Both BRE and ERE search for a match within a line, but several operators have different spellings. In BRE, parentheses, braces, and alternation commonly need backslashes to become special. ERE makes the same constructs readable without those backslashes.

Intent BRE (default) ERE (-E)
Group two alternatives (cat|dog) (cat|dog)
Repeat a preceding item two to four times ab{2,4} ab{2,4}
Match either word at the start of a line ^(ERROR|WARN): ^(ERROR|WARN):

For a simple literal, the modes are interchangeable:

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

Use ERE when alternatives, groups, or intervals are central to the condition. It reduces visual escaping and makes review easier. Keep BRE when maintaining an existing command or when a minimal pattern does not benefit from ERE.

POSIX defines an ERE match as matching some part of an input line, excluding the terminating newline. That is why an unanchored expression such as error also matches database error: retrying.

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Use options to control precision and case

Ignore case with -i

-i makes alphabetic matching case-insensitive:

grep -i 'warning' app.log

Combine it with -w when the term should stand alone:

grep -iw 'warning' app.log

Match a whole word with -w

-w restricts a match to a word boundary as grep defines it. It prevents a search for warning from selecting a longer word such as warningly, while still matching a line such as warning: disk nearly full. It is a word test, not a whole-line test; surrounding punctuation and other words may remain.

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

Match the entire line with -x

-x selects only lines whose complete content matches the pattern:

grep -x 'READY' status.txt

This is useful for allowlists, state files, and one-value-per-line inputs. A line containing READY now will not match.

Invert selection with -v

-v prints lines that do not match:

grep -v '^#' config.conf

That command removes lines beginning with #, but it does not remove blank lines. If both comments and blanks must be excluded, express both cases in one pattern and invert it, for example with ERE:

grep -Ev '^(#|$)' config.conf

Options can be combined when their meanings do not conflict. For example, grep -ivw 'warning' file performs a case-insensitive whole-word search and prints matching lines.

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

Search for alternatives and pattern lists

Put alternatives in one ERE

Use the ERE alternation operator when a short list belongs to one logical condition:

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

Grouping lets you attach an anchor or suffix to the alternatives as a unit:

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
grep -E '^(ERROR|WARN):' app.log

The anchor applies to the group, so only lines beginning with either label qualify.

Use repeated -e options

Separate -e options are clearer when patterns are independent or contain different syntax:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
grep -e 'timeout' -e 'connection refused' app.log

They also safely handle a pattern beginning with -. Grep prints a line if it matches at least one supplied pattern.

Read many patterns from a file with -f

Store one pattern per line in a file and pass it with -f:

grep -f patterns.txt access.log

Each line in patterns.txt is interpreted as a pattern in the selected matcher family. This keeps a growing list out of shell quoting and makes it easy to review or version-control the list. If the entries are literal phrases rather than regexes, add -F so punctuation is not treated as metacharacters:

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

Choose literal matching when regex is unnecessary

Regex syntax is useful only when you need pattern behavior. For an exact phrase containing characters such as ., *, or ?, -F avoids escaping and prevents accidental broad matches:

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 -F 'version 1.2.3' release-notes.txt

Use -F for large lists of literal identifiers as well. Use the default BRE or -E when the expression must vary by character, position, repetition, or alternative.

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

Search one file, standard input, or a directory tree

Named files and standard input

A filename after the pattern restricts the search to that file. Omitting filenames makes grep read standard input, which is why it works naturally in pipelines:

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
cat access.log | grep -E ' 5[0-9][0-9] '
grep -E ' 5[0-9][0-9] ' access.log

The second form avoids an unnecessary cat process and is easier to extend with additional filenames.

Recursive traversal

When the text may be spread across a directory tree, use grep’s recursive options rather than invoking it separately for every file:

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 -RInE 'TODO|FIXME' src/

Here -R traverses directories, -I skips binary files, and -n includes line numbers; -E enables alternation. Traversal can include generated files, dependency trees, or very large data, so narrow the starting directory and pattern when possible. If you need behavior that follows or avoids symbolic links, check the distinction between your platform’s recursive options before using the command in a script.

Locale, encoding, and binary-data caveats

Character ranges and POSIX classes are affected by the current locale. A script that must behave consistently across machines should choose an intentional locale and prefer named POSIX classes where they express the requirement. Do not assume that a range such as [a-z] has exactly the same ordering or membership under every locale.

GNU grep may classify input containing null bytes or encoding errors as binary. In that situation it can suppress the normal stream of matching lines and instead report that a binary file matches. This is a property of the input classification, not proof that the regex is wrong. If the file is known to be text despite the bytes it contains, use the text-handling option appropriate to your GNU grep version, or preprocess the data into a text encoding you control. For portable scripts, document the expected encoding rather than silently relying on a terminal’s locale.

PCRE mode has an additional portability caveat: -P may be unavailable or may emit different warnings on different GNU grep builds. Treat it as an environment-dependent feature, not a baseline requirement for Linux shell scripts.

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

A repeatable workflow for writing a grep regex

  1. Decide whether the input is literal or patterned. Start with -F for a phrase or identifier that should be taken literally.
  2. Define the match boundary. Choose an unanchored substring, a whole word with -w, or a whole line with -x. Use ^ and $ when the boundary is part of a larger expression.
  3. Select the dialect. Keep BRE for simple or existing expressions; use -E for readable groups, alternation, and intervals; reserve -P for required PCRE features.
  4. Add character constraints. Replace broad dots with bracket expressions or POSIX classes when the allowed characters matter.
  5. Quote the pattern. Single-quote it unless intentional shell expansion is required.
  6. Test against positive and negative examples. Include lines that should match, near misses such as longer words, and empty or comment lines when those are relevant.
  7. Scale the input only after the pattern is correct. Move from one file to a pipeline or recursive directory search, then add line numbers or binary-file handling if needed.

Common failure modes and fixes

The pipe character is printed literally or behaves strangely

If you run grep 'error|failed' file without ERE mode, the expression is interpreted using BRE rules, where alternation is not written the same way. Use grep -E 'error|failed' file, or write the BRE form with the required escaping.

Parentheses or braces do not group or repeat

Check the dialect first. In BRE, grouping and interval expressions commonly require backslashes; in ERE, write (...) and {m,n} directly after adding -E.

A pattern matches too many lines

An unanchored regex searches any part of a line, and a dot matches almost any character. Add ^ or $, use -w or -x, and replace . with a narrower bracket expression.

A pattern beginning with a dash is treated as an option

Pass it with -e or place -- before the pattern. Quoting alone does not stop option parsing.

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

Expected text is missing from the output

Check case with -i, verify that -v was not accidentally used, and inspect whether -x or -w made the condition stricter than intended. If grep reports a binary match instead of lines, review the file’s bytes and encoding.

Quick decision table

Need Command shape Reason
Literal text grep -F 'text' file Metacharacters remain literal.
Either of two terms grep -E 'one|two' file ERE alternation is readable.
Case-insensitive whole word grep -iw 'warning' file Combines case folding and word boundaries.
Exact line grep -x 'READY' file Rejects surrounding characters.
Exclude comments grep -v '^#' file Inverts a beginning-of-line test.
Many patterns grep -f patterns.txt file Keeps one pattern per file line.
Pattern starts with - grep -e '-pattern' file Marks the argument as a pattern.
Directory tree grep -R 'pattern' directory/ Traverses files below the chosen directory.

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.