π Search - simple bash script
π 2025-12-05 17:20
Here's a simple bash script that searches files for keywords. I use this script to power the search on this gemini capsule.
You can test the search script from my blog or via the link below:
π Search Sava.Rocks blog posts
Features
- π¦ Searches
- π¨οΈ Prints results
- π¨οΈ Shows snippets for each result
Be aware, if you want to use this script there are 2 things you should keep in mind:
- my blog posts are contained in the "blog" folder. Each post has it's own folder named as it's slug: /blog/slug-of-the-post/
- the script searches only the folders inside the blog folder (-mindepth 2), and only files named as: index.gmi
β Make sure to adapt to your blog structure β
Code
And now, the script:
#!/bin/sh
SEARCH_DIR="./blog/"
MAX_RESULTS=50
# Everything after '?' in /search/?TERM is in QUERY_STRING
QUERY="$QUERY_STRING"
# Decode %20 etc. to spaces
QUERY=$(printf '%b' "$(echo "$QUERY" | sed 's/%/\\x/g')")
# If empty, prompt Gemini client
if [ -z "$QUERY" ]; then
printf "10 What are you looking for?\r\n"
exit 0
fi
# GREP MODE (fixed string, case-insensitive)
GREP_CMD="grep -liF"
printf "20 text/gemini\r\n"
printf "# π΅ Sava.Rocks - Search results for: %s\r\n" "$QUERY"
printf "\r\n"
printf "=> /search/ π Start another search\r\n"
# SEARCH EXECUTION
RESULTS=$(find "$SEARCH_DIR" -mindepth 2 -type f -name "index.gmi" ! -path "$SEARCH_DIRindex.gmi" -print0 \
| xargs -0 $GREP_CMD "$QUERY" 2>/dev/null \
| head -n "$MAX_RESULTS")
[ -z "$RESULTS" ] && { printf "No results.\r\n"; exit 0; }
printf "## Results in Sava's blog posts:\r\n"
printf "\r\n"
# TITLE EXTRACTOR
# GET'S THE TEXT FROM THE FIRST LINE STARTING WITH #
get_title() {
grep -m 1 '^#' "$1" | sed 's/^# *//'
}
# FORMAT RESULTS
printf '%s\n' "$RESULTS" | while IFS= read -r FILE || [ -n "$FILE" ]; do
# Normalize the path so itβs relative to the current directory
REL=$(printf '%s' "$FILE" | sed 's#^./##')
BLOG_SLUG=$(printf "%s" "$REL" | sed -E 's#^blog/##' | sed -E 's#/index\.gmi$##')
LINK="/blog/$BLOG_SLUG/"
TITLE=$(get_title "$FILE")
[ -z "$TITLE" ] && TITLE="$BLOG_SLUG"
# First matching line as snippet (trim to 280 chars)
SNIPPET=$(grep -i -m 1 -F "$QUERY" "$FILE" | cut -c1-280)
printf "=> %s %s\r\n" "$LINK" "$TITLE" # RESULT LINK
printf "> %s\r\n" "$SNIPPET" # RESULT SNIPPET
printf "\r\n"
done
printf "\r\n"
printf "=> /blog/ πΆ Back to my blog"
printf "\r\n"
Go ahead and add search to your gemini gemlog π΅οΈ.
πΆ Back to Fun Stuff