Powerful regular expression pattern searching.

OR

If you want to search for multiple conditions then you can use OR statements within the regular expression/pattern. There are two approaches, either escape the OR symbol, i.e. \| or use the -E flag.

snippet.bash
# These two are equivalent
grep -E 'a|b' my_file.csv
grep 'a\|b' my_file.csv

From files

If you have multiple conditions or terms you wish to be searched for using grep you can use the -f flag to pass a file of terms to search for.

snippet.bash
# Search for terms in 'file.txt' in files ending in *.py
grep -f file.txt *.py

Chained searches

Here is one solution when you want to chain searches on the output of previous searchesuses recursion which Bash does support and is rarely used, but when it is can be incredibly powerful.

snippet.bash
function chained-grep {
    local pattern="$1"
    if [[ -z "$pattern" ]]; then
        cat
        return
    fi    
 
    shift
    grep -- "$pattern" | chained-grep "$@"
}

Links

Specific Solution

linux/bash/grep.txt · Last modified: 2022/02/08 09:55 by admin
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0