Skip to content

Instantly share code, notes, and snippets.

@bimlas
Last active May 1, 2020 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bimlas/2d65b1e63c0470225ef7db07ab918e9f to your computer and use it in GitHub Desktop.
Save bimlas/2d65b1e63c0470225ef7db07ab918e9f to your computer and use it in GitHub Desktop.
Full text search with plain, vanilla Linux tools (Bash, Grep): Search for files that contain each word
#!/bin/bash
# grep-full-text-search.sh: Search for files that contain each word
#
# Usage:
# grep-full-text-search.sh GREP_OPTIONS PATTERNS FILE...
#
# Examples:
#
# # Show matches
# grep-full-text-search.sh --color -Hni "multiple keywords" *.txt
#
# # List only filenames
# grep-full-text-search.sh -l "multiple keywords" *.txt
#
# # Usage in Vim
# :set grepprg=grep-full-text-search.sh\ -Hni
# :grep "multiple keywords" *.txt
#
# ========================== bimlas.gitlab.io ================================
grep_args=''
while ( echo "$1" | grep '^-' > /dev/null ); do
grep_args="$grep_args $1"
shift
done
keywords=$1; shift
file_list=$(printf "%s\n" "$@")
for current in $keywords ; do
file_list=$(echo "$file_list" | xargs --delimiter="\n" grep --files-with-matches $grep_args "$current")
done
if [ "z$file_list" == "z" ]; then
exit 1
fi
for current in $keywords; do
grep_args="$grep_args -e $current"
done
echo "$file_list" | xargs --delimiter="\n" grep $grep_args
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment