Skip to content

Instantly share code, notes, and snippets.

@IamLizu
Last active March 20, 2019 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IamLizu/3aa902bf7f17b483d018a4eaeeb66535 to your computer and use it in GitHub Desktop.
Save IamLizu/3aa902bf7f17b483d018a4eaeeb66535 to your computer and use it in GitHub Desktop.
A simple shell script that search a specified directory for a term inside the files, the script has the ability to limit the results.
# Author: S M Mahmudul Hasan
# Website: https://www.iamlizu.com
# Programming Forum - https://discuss.codepractice.net
# Email: hasan@codepractice.net
# Syntax: ./search [filepath - the location of the dir] [term - the keyword you want to search] [limit - integer to limit results]
#!/bin/sh
filepath="$1" #here assigning a veriable is not necessary rather not suggested.
string="$2" # "
limit="$3" # "
echo ---------------------------Searching:-------------------------
echo " "
echo "Searching dir: $filepath"
echo "Listing all files from the dir.../"
echo " "
ls $filepath # Using 'ls' to list files of the specified dir.
echo " "
echo -n "Total files in dir: "
ls $filepath | wc -l # counting total files in the dir
echo -n "Total unique file types in dir: "
ls | grep -Eo "\..+" | sort -u | wc -l # counting total unique file types
echo "Listing unique file types../"
ls | grep -Eo "\..+" | sort -u | cut -c 2- | tr "\n" " " # Lisiting unique file types
echo "\n"
echo "You searched for: $string"
echo "Your search is limited to $limit result(s)"
echo " "
grep -n -o $string $filepath/* | head -n $limit # grep to search the term and using head to limit the search
echo " "
echo --------------------------Search Complete--------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment