Skip to content
System

Speeding up grep on large files in Linux

Avatar illustré de Julien Macé 7 min read
Poste d’administration Linux consacré à l’analyse de journaux volumineux
Illustration éditoriale générée : analyse prudente de journaux Linux volumineux. Ce n’est pas une mesure de performance.

A search on a large application.log can take time, but the timer alone does not indicate whether grep is reading too many files, displaying too many lines, or applying a costly pattern. Before comparing commands, identify the file, ensure it is readable and stable, and then keep a full search as a reference. The paths below are examples to be adapted to your system.

Linux administration workstation dedicated to analyzing large logs
Editorial illustration generated: careful analysis of large Linux logs. This is not a performance measure.

Identify the file and establish a complete search

Start by confirming the tool, the path, the size, the modification date, and your read permissions. Use a frozen copy of the log if the service is still writing to it.

grep --version
test -f application.log && test -r application.log
stat -c '%n : %s bytes, modified %y' -- application.log
test -x /usr/bin/time

The stat command describes the target without scanning its content. If a check fails, stop: verify the path or file access instead of widening the search to the entire system. Logs may contain addresses, identifiers, or tokens; do not copy their output to a shared space without examining it.

Then launch a thorough and readable search:

grep -nF -e 'ERROR' -- application.log
rc=$?
printf 'Grep code: %sn' "$rc"

-n adds the line number. -F interprets ERROR as literal text. -e specifies the pattern, and -- indicates that the following arguments are paths, even if they start with a hyphen. For a file containing errors, the command displays each matched line; code 0 means at least one line matches. Code 1 means no lines match. Code 2 indicates an error, such as a missing or unreadable file. Keep diagnostics on stderr visible: an empty result with an error is not a successful search.

This reference fixes the pattern and the corpus. It allows checking subsequent changes instead of confusing a shorter output with faster processing.

Narrow down the files searched before changing the pattern

If you are only searching through the logs of a service, name its files instead of launching a broad recursion. For a short list, directly pass the relevant paths to grep. Verify them beforehand with test -f and test -r if their presence or access is not guaranteed.

To select .log files from a tree while explicitly leaving out archives, first inspect the list:

find . -type d -name archives -prune -o -type f -name '*.log' -print

After confirming that this scope matches your question, you can directly pass the paths to grep:

find . -type d -name archives -prune -o -type f -name '*.log' 
  -exec grep -HnF -e 'ERROR' -- {} +

-prune prevents find from descending into the excluded folder. -exec ... {} + batches the paths; it does not ensure that a single invocation will suffice for a very large list. -H keeps the filename in the output, even when a batch contains only one file. The paths are passed as arguments without incorrect splitting on spaces. Keep stderr visible: the aggregated status of find with -exec ... + does not always distinguish a lack of matches from an error of grep in a batch. A tree modified during traversal is not a snapshot.

Another possibility, with GNU grep, is targeted recursion:

grep -rHnF --include='*.log' --exclude='*.gz' 
  --exclude-dir=archives -e 'ERROR' -- .

The exclusions are visible in the command and remain to be adapted to the actual files in use. -r traverses directories without following symbolic links encountered during descent; do not replace it with -R, which also follows these links and may widen the corpus. Excluding files reduces work since some are no longer searched: this is not an optimization with equivalent results. A single very large file is not shortened by a directory exclusion.

Use -F and the C locale without changing matches

Keep -F when the pattern is a literal string, such as ERROR. Choose -E if the need describes a structure, for example, a line prefix followed by a separator. Do not combine -F and -E: these are two different ways to interpret the pattern. Do not transform a literal search into a regular expression just to try to save time.

A list can also be read with -f, one rule per line. To prepare a list of patterns for grep, check in particular that it does not contain an inadvertent empty line: an empty pattern can select all lines.

For a case-sensitive ASCII pattern, LC_ALL=C is a candidate to compare:

LC_ALL=C grep -nF -e 'ERROR' -- application.log

The C locale may make some processing more efficient, but it also changes the character rules. This is not a conversion of the file to UTF-8. Behaviors related to Unicode characters, to -i, to classes like [[:alpha:]], and to ranges like [a-z] may differ. Therefore, do not use this prefix if the meaning of the pattern depends on these rules; do not export it globally. Check the matches on the relevant corpus before interpreting a time. If grep indicates that a file is binary, check why grep treats the file as binary before choosing a response; do not mask the issue with a performance option.

Choose between all lines, a count, and a first proof

These options do not serve the same purpose. A shorter output does not mean that grep has read less data.

Mode Obtained result Stop moment What it does not prove
Full search All selected lines After the necessary traversal of the file That another pattern or corpus would be equivalent
-m 1 At most one line selected per file After the first match of each file That other matches do not exist
-l The names of the files that contain a match On the first match of each file Full content or the number of lines
-c The number of lines selected per file After the necessary counting The number of occurrences: two patterns on one line count as one line
-q No output on stdout; code 0 on a match At the first match A comprehensive read: an error after the match may be masked

Choose -m, -l, or -q only if the question is genuinely about a first proof. -c reduces display, but the complete count generally requires traversing the file. None of these modes should be timed against a full search as if the expected results were identical.

Distinguish the delay of a pipe from the search time

--line-buffered asks grep to flush its output after each line when writing to a pipe. This may reduce the wait before display in a stream; it is not a universal acceleration of reading a large file. The following program in the pipe may itself buffer its output. The error messages from grep remain on stderr.

To control the statuses of both commands in Bash, copy PIPESTATUS immediately after the pipe, before any other command:

grep -nF -e 'ERROR' -- application.log | wc -l
codes=("${PIPESTATUS[@]}")
printf 'grep=%s wc=%sn' "${codes[0]}" "${codes[1]}"

The number displayed by wc does not replace the reference output, and its code alone does not reveal an error from grep. For a log being followed or finding an error with its context, the need is different from a comparison of exhaustive search.

Compare outputs before comparing times

Measure in a private workshop situated outside of the searched tree. mktemp creates a temporary directory; ensure its location is trustworthy and that it has enough space for two complete outputs. Work on a stable file. The example compares the same literal search, with and without the C locale:

workshop=$(mktemp -d "${TMPDIR:-$HOME}/grep-perf.XXXXXX") || exit 1
stat -c '%n : %s bytes, modified %y' -- application.log

/usr/bin/time -f 'real=%e user=%U sys=%S code=%x' 
  grep -nF -e 'ERROR' -- application.log > "$workshop/reference.txt"
ref_rc=$?

/usr/bin/time -f 'real=%e user=%U sys=%S code=%x' 
  env LC_ALL=C grep -nF -e 'ERROR' -- application.log > "$workshop/candidate.txt"
candidate_rc=$?

printf 'reference=%s candidate=%sn' "$ref_rc" "$candidate_rc"
cmp -- "$workshop/reference.txt" "$workshop/candidate.txt"
cmp_rc=$?
printf 'Comparison: %sn' "$cmp_rc"
stat -c '%n : %s bytes, modified %y' -- application.log

/usr/bin/time external displays the real time (real), CPU time user and system (user, sys), as well as the status of the command. The two outputs go into separate files; diagnostics remain visible. The status 0 from cmp means the outputs are identical, 1 that they differ, and 2 that the comparison failed.

Do not interpret times unless both searches have the expected status, no diagnostics have appeared, cmp returns 0, and the metadata of the input file is consistent before and after. An equality on one input does not prove equivalence for all future files. If you expect matches, also check a known line.

Repeat the measurements in an alternating order: the system cache, the load, and the storage may influence the result. Keep the same scope, the same options, and the same outputs; do not purge the cache in production. The gain is not measured here. An interruption leaves partial outputs, not complete proof.

The method assumes ordinary and stable text files. A rotation during the search, a giant line, a compressed or binary file, a live log, and the lack of space for results impose a distinct diagnosis. For a final check, reread the codes and compare the metadata of application.log again before keeping the results.

Sources to check

Share Facebook X WhatsApp LinkedIn Pinterest Reddit Email