grep reads files (or standard input) and prints the lines that match a pattern. For ordinary text searches, use a quoted basic regular expression (BRE), or add -E for extended regular expressions (ERE) when you need readable grouping, alternation, or repetition. For example, grep -E 'error|failed' app.log prints every line containing either word.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
This guide explains the regex dialects built into grep, shell quoting, precise line and word matching, multiple patterns, recursive searches, locale and binary-data behavior, and the common mistakes that produce surprising results.
As an Amazon Associate I earn from qualifying purchases.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWhat 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 supplied pattern. It normally writes each selected line to standard output, including the line’s original newline. A pattern is not required to match the entire line: unless you add anchors or a whole-line option, a match anywhere in the line selects it.
The general form is:
grep [options] 'pattern' file...
Examples:
# Search one file with the default regular-expression dialect
grep 'timeout' server.log
# Read from a pipeline instead of a named file
journalctl -b | grep -i 'failed'
Use single quotes around a pattern in shell commands. They prevent the shell from interpreting characters such as $, *, ?, parentheses, brackets, and the backslash before grep receives them. If you deliberately need shell variable expansion, use double quotes and understand which characters the shell will still process.
#1 Best Overall
- BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
- EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
- COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
- LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
- WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
Choose the grep matcher you actually need
GNU grep provides four matcher families. The option changes how the pattern is interpreted; it does not change the input files or the output format.
| Matcher | Option | Best for | Important behavior |
|---|---|---|---|
| Basic regular expressions (BRE) | -G, or no option |
Portable traditional grep patterns | Grouping, alternation, and interval repetition commonly need backslashes. |
| Extended regular expressions (ERE) | -E |
Readable alternatives, groups, and repetitions | (...), |, and {m,n} have their usual unescaped meanings. |
| Fixed strings | -F |
Literal text, not patterns | Metacharacters lose their regex meaning. This is often faster and safer for user-supplied text. |
| Perl-compatible regular expressions (PCRE) | -P |
Features not available in POSIX BRE or ERE | Availability and warnings vary by GNU grep build; portability is lower. |
Use the least powerful matcher that expresses the requirement. Choose -F when you need an exact literal substring, the default BRE for simple portable patterns, ERE for clear alternation and grouping, and PCRE only when a specific Perl-compatible feature justifies its portability cost.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesLiteral search versus regex search
Suppose you need to find the literal text a.b. A regex interprets the dot as “any character,” so use fixed-string mode:
grep -F 'a.b' notes.txt
Alternatively, escape the dot in a regex:
grep 'a.b' notes.txt
For a list of strings supplied by another person or program, -F avoids treating punctuation as executable pattern syntax.
Regex building blocks for grep
grep tests a pattern against each input line (excluding the terminating newline). The following constructs cover most log, configuration, and source-code searches.
| Construct | Meaning | Example |
|---|---|---|
^ |
Beginning of the line | ^ERROR finds lines that start with ERROR. |
$ |
End of the line | done$ finds lines ending in done. |
. |
Any single character | gr.y can match gray or grey. |
[abc] |
One character from the bracket expression | gr[ae]y matches gray or grey. |
[^abc] |
One character not in the bracket expression | [^0-9] matches a non-digit character. |
[0-9] |
A character in the stated range | [0-9][0-9] matches two digits. |
[[:digit:]] |
A POSIX character class | ^[[:digit:]] finds lines beginning with a digit. |
* |
Zero or more repetitions of the preceding atom | ab*c matches ac, abc, and abbc. |
|
Escapes a metacharacter or gives special meaning in BRE | . matches a literal dot. |
A bracket expression is one character, not a complete word. Thus [0-9] matches one digit; append a repetition or additional expressions when you need a multi-digit value. POSIX classes such as [[:digit:]], [[:lower:]], and [[:space:]] are preferable when locale portability matters.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →BRE and ERE: the syntax difference that causes most surprises
BRE is grep’s default. ERE, enabled with -E, makes several operators easier to read. The underlying idea is the same, but the characters that activate grouping, alternation, and interval repetition differ.
| Intent | BRE | ERE |
|---|---|---|
| Group two alternatives | (cat|dog) |
(cat|dog) |
| Either word | cat|dog |
cat|dog |
| Repeat two to four times | {2,4} |
{2,4} |
For example, these commands select lines beginning with either ERROR: or WARN::
Rank #2
- WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
- AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
- PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
- ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
- COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
# ERE: usually the clearest form
grep -E '^(ERROR|WARN):' app.log
# BRE equivalent
grep '^(ERROR|WARN):' app.log
Use ERE when the pattern contains several alternatives or nested groups. Use BRE when a small, traditional expression is sufficient or when you are targeting environments where default grep behavior is expected. Do not mix the two syntaxes casually: an ERE written with BRE escapes can match different text than intended.
Everyday search recipes
Find a simple term
grep 'timeout' server.log
This selects every line containing the character sequence timeout, regardless of where it occurs in the line. Matching is case-sensitive unless you add -i.
Ignore case
grep -i 'warning' server.log
-i performs case-insensitive matching. Combine it with other options when needed:
grep -iw 'warning' server.log
This finds a word such as warning or Warning, but not a longer word such as prewarning.
Search for alternatives
grep -E 'timeout|connection refused' server.log
The vertical bar means “or” in ERE. Quote the complete expression so the shell passes the bar to grep. Parentheses control which part is grouped:
grep -E '^(ERROR|WARN):' app.log
Without the parentheses, the anchor would apply only to the first alternative in many expressions, producing a broader match than intended.
Match a whole word
grep -w 'warning' server.log
-w asks grep to select matches that form whole words according to grep’s word-character rules. It is useful for identifiers and status words, but it is not a universal natural-language tokenizer: punctuation and non-ASCII word boundaries can depend on the locale.
Match an entire line
grep -x 'READY' status.txt
-x selects only lines whose complete contents match the pattern. It is equivalent in intent to adding both anchors:
Rank #3
- Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
- Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
- Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
- ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
- Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
grep '^READY$' status.txt
The option is easier to read when the requirement is explicitly “the entire line.”
Select lines that do not match
grep -v '^#' config.conf
-v inverts selection. The command above prints lines that do not begin with #; it does not remove blank lines. To ignore both comments and empty lines, use an ERE that matches either case, then invert it:
Free tools Windows power users keep installed
One-click scans. No signup required.
grep -Ev '^(#|$)' config.conf
Combine precision options
Options can be combined when each answers a different question. For example, this finds whole-word occurrences of either error or failed, ignoring case:
grep -Eiw 'error|failed' app.log
Keep the pattern quoted even when it contains no obvious shell metacharacters; it makes later edits safer.
Multiple patterns and patterns that begin with a hyphen
Repeat -e for a short list
grep -e 'timeout' -e 'connection refused' server.log
Each -e supplies one pattern, and a line matching any supplied pattern is selected. This form is convenient when the alternatives are assembled by a script or when each pattern deserves separate quoting.
Read patterns from a file
grep -f patterns.txt access.log
patterns.txt contains one pattern per line. The patterns are interpreted using the selected matcher, so add -E if the file contains ERE syntax:
Recommended Free Tools
grep -E -f patterns.txt access.log
Blank lines and whitespace in the pattern file are significant in ways that depend on the exact pattern; create the file deliberately and inspect it when a result seems unexpectedly broad.
Protect a pattern that starts with -
A pattern beginning with a hyphen can be mistaken for an option. Use -e:
Rank #4
- Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
- Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
- 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
- Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
- USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
grep -e '-pattern' file.txt
On systems that support the conventional option terminator, this also works:
grep -- '-pattern' file.txt
-e is explicit and remains useful when several patterns are present.
Searching directories and controlling the input
grep can search more than one file. Supplying multiple names prints the filename before each matching line, which helps identify the source:
grep -E 'ERROR|WARN' app.log worker.log
For directory trees, GNU grep supports recursive options. -r follows symbolic links encountered while traversing directories according to grep’s recursive behavior; -R follows all symbolic links. Use recursion intentionally, because it can include generated files, caches, binary files, and very large trees.
grep -RIn --include='*.conf' 'timeout' /etc/myapp
-Rsearches recursively while following symbolic links.-Iskips binary files.-nprints the matching line number.--include='*.conf'limits traversal results to names matching the shell-style file pattern.
The --include value is a filename filter, not a regular expression. Keep its wildcard quoted so the current shell does not expand it before grep sees it. If you need to exclude a directory or filename pattern, GNU grep also provides corresponding --exclude and --exclude-dir options.
Useful output and status controls
grep’s output options let you turn a search into a script-friendly test or a compact report.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →-nprints line numbers.-Halways prints the filename;-hsuppresses it when multiple files are searched.-lprints only names of files with at least one match.-Lprints only names of files with no match.-cprints a count of matching lines per file, not necessarily a count of every individual match on a line.-oprints only the matching portions rather than complete lines (where supported by the grep implementation).-qsuppresses normal output and is useful when only the exit status matters.
In shell scripts, grep exits with status 0 when it finds a match, 1 when it finds none, and 2 when an error occurs. Distinguish “no match” from “could not read the file” instead of treating every nonzero status as the same failure:
if grep -q -E 'ready|running' status.txt; then
echo 'service state found'
else
case $? in
1) echo 'state not present' ;;
*) echo 'grep reported an error' >&2; exit 1 ;;
esac
fi
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Locale, character classes, and binary data
Locale affects ranges and classes
Character ranges and POSIX classes are interpreted in the current locale. A range such as [a-z] can behave differently from a simple ASCII-only assumption in a locale with additional collation rules. When portability across systems matters, POSIX classes such as [[:lower:]] communicate intent and respect the active locale. If a script requires byte-oriented, locale-independent behavior, set its locale deliberately and document that choice rather than relying on the operator’s interactive environment.
Best Value
- Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
- Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
- Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
- Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
- Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
Binary input is not ordinary text
GNU grep can classify input containing null bytes or encoding errors as binary. In that situation it may suppress normal matching details and report that a binary file matches. If the data is known to be text but contains unusual bytes, GNU grep provides text-handling controls; use them only when you understand the encoding and the risk of terminal output containing control characters. The -I option is a safer choice for recursive source searches when binary files should simply be skipped.
When to use -P and when not to
grep -P enables Perl-compatible regular expressions in GNU grep. It can be useful for a feature unavailable in POSIX BRE or ERE, but support and diagnostics vary by build, distribution, and version. A script intended for many Unix-like systems should not assume that -P exists or behaves identically everywhere.
Before choosing PCRE, check whether a BRE or ERE expresses the requirement. ERE already handles ordinary grouping, alternation, and interval repetition, and is generally the better portability choice. Use PCRE only for a concrete PCRE feature and state that requirement in the script or documentation.
A practical decision framework
| Your requirement | Recommended form | Example |
|---|---|---|
| Find literal text exactly as typed | Fixed strings | grep -F 'a.b' file |
| Find a simple portable pattern | BRE (default) | grep '^timeout' file |
| Use readable alternatives or groups | ERE | grep -E '^(ERROR|WARN):' file |
| Require a whole word | -w with the appropriate matcher |
grep -iw 'warning' file |
| Require a complete line | -x, or both anchors |
grep -x 'READY' file |
| Search several patterns maintained separately | Repeated -e or -f |
grep -f patterns.txt file |
| Search a directory tree | Recursive grep with file filters | grep -RIn --include='*.conf' 'timeout' dir |
| Need a Perl-compatible-only feature | PCRE, after checking availability | grep -P 'pattern' file |
Troubleshooting patterns that do not behave as expected
The shell changed my pattern
Quote the pattern with single quotes. An unquoted * can be expanded to filenames, $ can trigger variable expansion, and a backslash can be consumed before grep receives it. If a pattern must contain a shell variable, isolate the variable deliberately and inspect the resulting value.
Parentheses or | do nothing
You may be using BRE syntax while writing an ERE. Add -E and write (...) and | plainly, or escape them for BRE as shown earlier. Do not add backslashes at random; each dialect has different operator rules.
The search matches too much
Add the missing boundary: ^ for the start, $ for the end, -w for a whole word, or -x for a complete line. Replace a broad dot with a bracket expression or a literal escaped dot when any-character matching is not intended.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
The search matches nothing
- Check case with
-i. - Check whether the text includes carriage returns, tabs, or trailing spaces.
- Confirm that you selected the intended dialect, especially after adding
-Eor-P. - For a pattern beginning with a hyphen, use
-e. - Test the expression against a small sample file before applying it recursively.
grep reports a binary file
The input contains bytes grep treats as binary. Skip such files with -I during recursive searches, or use an explicit text mode only when the file’s encoding and contents are known to be safe for terminal output.
A recursive search is slow or noisy
Narrow the tree and filenames with --include, exclude generated or vendor directories, skip binary files with -I, and use -l when you only need the names of matching files. A precise input set usually matters more than making the regex more complicated.
Quick Recap
A repeatable workflow
- Decide whether the search text is literal. If so, start with
-F. - Write the smallest pattern that states the requirement, then single-quote it.
- Use BRE for simple portable expressions or add
-Efor clear groups and alternatives. - Add boundaries such as
^,$,-w, or-xonly where the data model requires them. - Test against a short, representative file and inspect both matching and nonmatching examples.
- For many patterns, use repeated
-eoptions or a reviewed pattern file with-f. - For directory trees, constrain filenames and directories, decide how symbolic links should be handled, and account for binary data.
- In scripts, check grep’s exit status so “no match” is not confused with an input or option error.
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.




