Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- path=$1 # 1st arg is the path to be searched
- regex=$2 # 2nd arg is a regular expression
- searchTerm=$3 # 3rd arg is an optional search term
- startDir=`pwd` # Stores the starting path
- getDirs() { # Function to get the directories
- for i in "$1"/*; do # for the entire contents of the dir passed
- if [ -d "$i" ]; then # if a directory is found
- echo "$i" >> temp.txt # add it to temp
- getDirs "$i" # repeat the process for each dir found
- fi
- done
- }
- getFiles() { # Function to get files matching the regex
- for a in $directories; do
- cd "$a"
- temp=`ls -1 | grep $regex`
- for j in $temp; do
- echo "$a/"$j""
- done
- done
- }
- searchFiles() { # Function to search within files
- for a in $output1; do
- out=`grep -n "$searchTerm" $a | cut -d: -f 1` # Using colon as delimiter to remove the line returned by grep
- for i in $out; do
- echo "$a: line $i"
- done
- done
- }
- numArgs=$#
- echo "$path" >> temp.txt # Adding original path as the getDirs function will not find it
- getDirs $path # Getting directories to search
- directories=`cat temp.txt`
- output1=`getFiles`
- cd $startDir
- if [ $numArgs == 3 ]; then # If a search term was specified by the user
- searchFiles # Then look for that search term in the files found
- else
- echo "$output1"
- fi
- rm temp.txt # Removing temporary files
- exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement