Advertisement
Guest User

script

a guest
Jan 4th, 2013
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.37 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. path=$1         # 1st arg is the path to be searched
  4. regex=$2        # 2nd arg is a regular expression
  5. searchTerm=$3       # 3rd arg is an optional search term
  6. startDir=`pwd`      # Stores the starting path
  7.  
  8. getDirs() {     # Function to get the directories
  9.    
  10.    
  11.     for i in "$1"/*; do         # for the entire contents of the dir passed
  12.         if [ -d "$i" ]; then        # if a directory is found
  13.             echo "$i" >> temp.txt   # add it to temp
  14.             getDirs "$i"        # repeat the process for each dir found
  15.         fi
  16.     done
  17. }
  18.  
  19. getFiles() {        # Function to get files matching the regex
  20.    
  21.     for a in $directories; do
  22.         cd "$a"
  23.         temp=`ls -1 | grep $regex`
  24.        
  25.         for j in $temp; do
  26.             echo "$a/"$j""
  27.         done
  28.     done
  29. }
  30.  
  31. searchFiles() {         # Function to search within files
  32.  
  33.    
  34.     for a in $output1; do
  35.         out=`grep -n "$searchTerm" $a | cut -d: -f 1`   # Using colon as delimiter to remove the line returned by grep
  36.         for i in $out; do
  37.             echo "$a: line $i"
  38.         done
  39.     done
  40. }
  41.  
  42. numArgs=$#
  43.  
  44. echo "$path" >> temp.txt            # Adding original path as the getDirs function will not find it
  45. getDirs $path                   # Getting directories to search
  46.  
  47. directories=`cat temp.txt`
  48.  
  49. output1=`getFiles`
  50.  
  51. cd $startDir
  52.  
  53. if [ $numArgs == 3 ]; then  # If a search term was specified by the user
  54.     searchFiles     # Then look for that search term in the files found
  55. else
  56.     echo "$output1"
  57. fi
  58.  
  59. rm temp.txt                     # Removing temporary files
  60. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement