Daily Archives: 22 February 2017


grep: How to match lines using any of multiple patterns

Recently, we needed to filter the results of ps x using two different patterns.
The first pattern was ./ where we needed to match that exact character sequence.
The . period character is treated as a special character in regular expressions (it matches a single character of any value, except for the end of line), so we decided to use the -F parameter to remove this special handling.
Doing this change prevented us from writing a regular expression that uses the OR | operator.

-F (or --fixed-strings) is a matching control option that instructs grep to interpret the patterns as a list of fixed strings (instead of regular expressions), separated by newlines, any of which is to be matched.
We tried assigning the different patterns as different lines to a variable and then using them on the pipe, like in the following example:

patterns="./
banana";
ps x | grep -F $patterns;

..but it failed.

Solution

grep supports a matching control option -e that allows us to define multiple patterns using different strings.

-e PATTERN (or --regexp=PATTERN) uses the value PATTERN as the pattern. If this option is used  multiple times or it is combined with the -f (--file) option, grep will search for all patterns given.

In the end, our command was transformed to the following, which worked just fine!

ps x | grep -F -e "./" -e "banana";

A small note on how we use valgrind

valgrind is a suite of tools for debugging and profiling programs.
We use it for debugging and profiling Linux executable files.

Despite the fact that it can do a whole lot of stuff, usually we use it as follows (when we do not forget) to test our applications for memory leaks:

valgrind --show-leak-kinds=all --leak-check=full $application $application_arguments;

The options we chose are the following:

  • --show-leak-kinds=all It will show all leaks (definite, indirect, possible, reachable) in the full leak search (see next bullet)
  • --leak-check=full this option instructs valgrind to search for memory leaks when the client program finishes.
    Each individual leak will be shown in detail and be counted as an error.

These options are extremely useful as they will catch a lot of little leaks that you might have missed (e.g. closing a file, freeing some memory, …)